0% found this document useful (0 votes)
8 views

Tutorials

C# (C-Sharp) is a versatile programming language developed by Microsoft, primarily used for building applications across various platforms, including mobile, web, and games. The language, which is object-oriented and easy to learn, has a strong community and extensive support, with its latest version being C# 12 released in November 2023. Key features include variable types, data structures like structs, asynchronous programming, and a distinction between value types and reference types.

Uploaded by

vishwathirty3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Tutorials

C# (C-Sharp) is a versatile programming language developed by Microsoft, primarily used for building applications across various platforms, including mobile, web, and games. The language, which is object-oriented and easy to learn, has a strong community and extensive support, with its latest version being C# 12 released in November 2023. Key features include variable types, data structures like structs, asynchronous programming, and a distinction between value types and reference types.

Uploaded by

vishwathirty3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 110

C#

C#

C# (C-Sharp) is a programming language developed by Microsoft that runs on the .NET


Framework.

C# is pronounced "C-Sharp".

C# has roots from the C family, and the language is close to other popular languages
like C++ and Java.

The first version was released in year 2002. The latest version, C# 12, was released in
November 2023.

C# is used for:

• Mobile applications
• Desktop applications
• Web applications
• Web services
• Web sites
• Games
• VR
• Database applications
• And much, much more!

Applications written in C# use the .NET Framework, so it makes sense to use Visual Studio, as
the program, the framework, and the language, are all created by Microsoft.

Why Use C#?


• It is one of the most popular programming languages in the world
• It is easy to learn and simple to use
• It has huge community support
• C# is an object-oriented language which gives a clear structure to programs and allows
code to be reused, lowering development costs
• As C# is close to C, C++ and Java, it makes it easy for programmers to switch to C# or
vice versa

Comments

0|Page
can be used to explain C# code, and to make it more readable. It can also be used to
prevent execution when testing alternative cod

Single-line Comments
Single-line comments start with two forward slashes (//).
Multi-line Comments
Multi-line comments start with /* and ends with */.

Namespace
Namespaces play an important role in managing related classes in C#. The .NET
Framework uses namespaces to organize its built-in classes. For example, there are
some built-in namespaces in .NET such as System, System.Linq, System.Web, etc.
Each namespace contains related classes.

A namespace is a container for classes and namespaces.

C# Variables
Variables are containers for storing data values.

• Variable names must be unique.


• Variable names can contain letters, digits, and the underscore _ only.
• Variable names must start with a letter.
• Variable names are case-sensitive,

In C#, there are different types of variables (defined with different keywords), for example:

• int - stores integers (whole numbers), without decimals, such as 123 or -123
• double - stores floating point numbers, with decimals, such as 19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
• string - stores text, such as "Hello World". String values are surrounded by double
quotes
• bool - stores values with two states: true or false

var
C# 3.0 introduced var keyword to declare method level variables without
specifying a data type explicitly.

var can be used to declare any built-in data type or a user-defined type or an
anonymous type variable.

The keyword var is used to declare implicit type variables in C#

1|Page
Constants
which means unchangeable and read-only:
you can add the const keyword in front of the variable type. PI (3.14159...).

You cannot declare a constant variable without assigning the value.

Struct
C#, struct is the value type data type that represents data structures. It can contain a
parameterized constructor, static constructor, constants, fields, methods, properties,
indexers, operators, events, and nested types.

structcan be used to hold small data values that do not require inheritance, e.g. coordinate
points, key-value pairs, and complex data structure.

When to Use Structs in C# Structs are best used when you need to represent simple data
types, such as integers, strings, or other basic data types. They are also useful when you
need to work with large datasets, such as arrays or lists, where performance is critical.

Use struct

• If all the member fields are value types.


• If instances of the type are small and short-lived or embedded to other
instances.
• If it logically denotes a single value, same as primitive types like int, double,
etc.
• If the size of the instance is below 16 bytes.
• If it will not be boxed and unboxed again and again.

Display Variables
The WriteLine() method is often used to display variable values to the console window.

To combine both text and a variable, use the + character:

Declare Many Variables


To declare more than one variable of the same type, use a comma-separated list:

int x = 5, y = 6, z = 50;

Console.WriteLine(x + y + z);

C# Identifiers

2|Page
All C# variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).

Note: It is recommended to use descriptive names in order to create understandable and


maintainable code:

C# Data Types
As explained in the variables chapter, a variable in C# must be a specified data type:

int myNum = 5; // Integer (whole number)

double myDoubleNum = 5.99D; // Floating point number

char myLetter = 'D'; // Character

bool myBool = true; // Boolean

string myText = "Hello"; // String

C# Type Casting
Type casting is when you assign a value of one data type to another type.

In C#, there are two types of casting:

• Implicit Casting (automatically) - converting a smaller type to a larger type size


char -> int -> long -> float -> double

• Explicit Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char

Why Casting Conversion?


• Many times, there's no need for type conversion. But sometimes you have to. Take a
look at the next chapter, when working with user input, to see an example of this.

User Input
• You have already learned that Console.WriteLine() is used to output (print) values.
Now we will use Console.ReadLine() to get user input.
• In the following example, the user can input his or hers username, which is stored in
the variable userName.
• The Console.ReadLine() method returns a string.
Console.WriteLine("Enter your age:");

3|Page
int age = Console.ReadLine();

Operators
Operators are used to perform operations on variables and values.

+Addition, - Subtraction,*Multiplication, / Division, % Modulus, ++ Increment ,--


Decrement.

Assignment Operators
Assignment operators are used to assign values to variables.

=:, =+, =- ,=*,=%

Comparison Operators
Comparison operators are used to compare two values (or variables).

The return value of a comparison is either True or False.

Console.WriteLine(x > y);

Logical Operators
As with comparison operators, you can also test for True or False values with logical
operators.

&& logicl and ,|| logical or ,=! Logical not

Math
The C# Math class has many methods that allows you to perform mathematical tasks on numbers

Math.Max(x,y) , Math.Min(x,y) , Math.Sqrt(x) , Math.Round(), Math.Abs(x)

C# Strings
Strings are used for storing text.

A string variable contains a collection of characters surrounded by double quotes:

You can also use the string.Concat() method to concatenate two strings:

String Interpolation ; string name = $"My full name is: {firstName} {lastName}";

4|Page
Access Strings ;\
string myString = "Hello";

Console.WriteLine(myString[1]); // Outputs "e"

Console.WriteLine(myString.IndexOf("e")); // Outputs "1"

string lastName = name.Substring(myString);

Another useful method is Substring(), which extracts the characters from a string, starting
from the specified character position/index, and returns a new string. This method is often
used together with IndexOf() to get the specific character position:

StringBuilder
The StringBuilder doesn't create a new object in the memory but dynamically
expands memory to accommodate the modified string.
This behavior would hinder the performance if the original string changed
multiple times by replacing, appending, removing, or inserting new strings in the
original string.

1. StringBuilder is mutable.
2. StringBuilder performs faster than string when appending multiple string values.
3. Use StringBuilder when you need to append more than three or four strings.
4. Use the Append() method to add or append strings to the StringBuilder object.
5. Use the ToString() method to retrieve a string from the StringBuilder object.

Difference between String and string

Essentially, there is no difference between string and String (capital S) in C#.

String (capital S) is a class in the .NET framework in the System namespace. The
fully qualified name is System.String. Whereas, the lower case string is an alias of
System.String.

Difference between String and StringBuilder

both string and StringBuilder are used to represent text.


a string is immutable.
It means a string cannot be changed once created. For example, a new string,
"Hello World!" will occupy a memory space on the heap.

5|Page
Now, changing the initial string "Hello World!" to "Hello World! from Tutorials
Teacher" will create a new string object on the memory heap instead of modifying
an original string at the same memory address.
This impacts the performance if you modify a string multiple times by replacing,
appending, removing, or inserting new strings in the original string.
StringBuilder

StringBuilder sb = new StringBuilder("Hello World!");


sb.Append("from Tutorials Teacher.");

C# Booleans
C# has a bool data type, which can take the values true or false.

• YES / NO
• ON / OFF
• TRUE / FALSE

Nullable types
Nullable types represent the Null value as well the actual range of that data type.

Anonymous Type
Example: Anonymous Type
var student = new { Id = 1, FirstName = "James", LastName = "Bond" };

• an anonymous type is a type (class) without any name that can contain public read-
only properties only. It cannot contain other members, such as fields, methods,
events, etc.
• You create an anonymous type using the new operator with an object
initializer syntax. The implicitly typed variable- var is used to hold the reference of
anonymous types.

Dynamic Types
• C# 4.0 (.NET 4.5) introduced a new type called dynamic that avoids compile-time type
checking. A dynamic type escapes type checking at compile-time; instead, it resolves
type at run time.
• A dynamic type variables are defined using the dynamic keyword.

Example: dynamic Variable


dynamic MyDynamicVar = 1;
Console.WriteLine(MyDynamicVar.GetType());

6|Page
Asynchronous Programming?
In asynchronous programming, the code gets executed in a thread without having to wait
for an I/O-bound or long-running task to finish.

Microsoft recommends Task-based Asynchronous Pattern to implement asynchronous


programming in the .NET Framework or .NET Core applications
using async , await keywords and Task or Task<TResult> class.

Threading in C#?
Threads are the backbone of any software application. In simple terms, a thread is a
single sequence of instructions that a process can execute. In C#,
the System.Threading namespace offers classes that allow you to manipulate threads.

Use;

Choosing single threading or multithreading in your application largely depends on the


tasks and their requirements.

async, await, and Task


An async keyword is a method that performs asynchronous tasks such as
fetching data from a database, reading a file, etc

Use async along with await and Task if the async method returns a value back to
the calling code. We used only the async keyword in the above program to
demonstrate the simple asynchronous void method.

The await keyword waits for the async method until it returns a value. So the
main application thread stops there until it receives a return value.

The Task class represents an asynchronous operation


and Task<TResult> generic class represents an operation that can return a
value. In the above example, we used await Task.Delay(4000) that
started async operation that sleeps for 4 seconds and await holds a thread until
4 seconds.

7|Page
The difference between const and static readonly

Declared using the static keyword. Declared using the readonly keyword. Declred using the const keyword.
The difference is that the value of a static readonly field is set at run time, and can thus
be modified by the containing class, whereas the value of a const field is set to a compile-
time constant
Value of the static members can be modified Readonly variable cannot be Constant variables
using ClassName.StaticMemberName . modified at run-time. It can only be cannot be modified
initialized or changed in the after declaration.
constructor.

Value Type and Reference Type


In C#, these data types are categorized based on how they store their value in the memory. C#
includes the following categories of data types:

1. Value type
2. Reference type
3. Pointer type

Value Type
A data type is a value type if it holds a data value within its own memory space. It
means the variables of these data types directly contain values.

All the value types derive from System.ValueType, which in-turn, derives from System.Object.

For example, consider integer variable int i = 100;

Reference Type
a reference type doesn't store its value directly. Instead, it stores the address where the
value is being stored. In other words, a reference type contains a pointer to another
memory location that holds the data.

For example, consider the following string variable:

string s = "Hello World!!";

8|Page
ref Keyword

C# supports value type and reference type data types. By default, the value type
variable is passed by value, and the reference type variable is passed by reference
from one method to another method in C#.

Pointers
Pointers are defined as a variable that contains the memory address of another variable.

out keyword

The out keyword can be used with variables and method parameters. The
out paramters are always passed by reference for both, the value type and
the reference type data types.
What is boxing?
Boxing is the process of converting a value type to the object type or any interface type
implemented by this value type. Boxing is implicit.

Boxing
int i = 10;
object o = i; //performs boxing

why is it named as boxing?

As you know, all the reference types stored on heap where it contains the address of the value
and value type is just an actual value stored on the stack

What is Unboxing?
Unboxing is the reverse of boxing. It is the process of converting a reference type to value
type. Unboxing extract the value from the reference type and assign it to a value type.

Unboxing is explicit. It means we have to cast explicitly.

Example: Unboxing
object o = 10;
int i = (int)o; //performs unboxing

Note:
Boxing and unboxing degrade the performance. So, avoid using it. Use generics to avoid
boxing and unboxing. For example, use List instead of ArrayList.

9|Page
Managed code and unmanaged code ;

Managed code is compiled to an intermediate language called Common Intermediate


Language (CIL) or Microsoft Intermediate Language (MSIL), which is then executed
by the CLR. Unmanaged Code is compiled directly to native code, which is executed
by the Operating System.

Compile time and Run time


Compile time is the period when the programming code (such as C#, Java, C,
Python) is converted to the machine code (i.e. binary code). Runtime is the period
of time when a program is running and generally occurs after compile time.

Conditions and If Statements


• Use if to specify a block of code to be executed, if a specified condition is true
• Use else to specify a block of code to be executed, if the same condition is false
• Use else if to specify a new condition to test, if the first condition is false
• Use switch to specify many alternative blocks of code to be executed

Short Hand If...Else (Ternary Operator)


includes a decision-making operator ?: which is called the conditional operator or
ternary operator. It is the short form of the if else conditions.
variable = (condition) ? expressionTrue : expressionFalse;

Switch Statements
Use the switch statement to select one of many code blocks to be executed.

This is how it works:

• The switch expression is evaluated once


• The value of the expression is compared with the values of each case
• If there is a match, the associated block of code is executed
• The break and default keywords will be described later in this chapter

The break Keyword


• When C# reaches a break keyword, it breaks out of the switch block.
• This will stop the execution of more code and case testing inside the block.
• When a match is found, and the job is done, it's time for a break. There is no need
for more testing.

10 | P a g e
The default Keyword
• The default keyword is optional and specifies some code to run if there is no case
match.

While Loop
Loops
• Loops can execute a block of code as long as a specified condition is reached.
• Loops are handy because they save time, reduce errors, and they make code more
readable.

While Loop
• The while loop loops through a block of code as long as a specified condition is True:
• the code in the loop will run, over and over again, as long as a variable (i) is less than

Note: Do not forget to increase the variable used in the condition, otherwise the loop
will never end!

Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.

Do not forget to increase the variable used in the condition, otherwise the loop will never
end!

For Loop
When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop:
for (statement 1; statement 2; statement 3)

// code block to be executed

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

11 | P a g e
Statement 3 is executed (every time) after the code block has been executed.

Nested Loops
It is also possible to place a loop inside another loop. This is called a nested loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

The foreach Loop


There is also a foreach loop, which is used exclusively to loop through elements in an array:

foreach (type variableName in arrayName)

// code block to be executed

Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was
used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.

Array
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.

To declare an array, define the variable type with square brackets:

Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

An array is the data structure that stores a fixed number of literal values (elements)
of the same data type. Array elements are stored contiguously in the memory.

12 | P a g e
In C#, an array can be of three types: single-dimensional, multidimensional, and
jagged array.

Sort an Array
There are many array methods available, for example Sort(), which sorts an array
alphabetically or in an ascending order:

Two-Dimensional Arrays
To create a 2D array, add each array within its own set of curly braces, and insert a comma (,)
inside the square brackets:

multidimensional arrays.
A multidimensional array is basically an array of arrays.

Arrays can have any number of dimensions. The most common are two-dimensional arrays
(2D).

Jagged Arrays ;
An array of array

A jagged array is an array of array. Jagged arrays store arrays instead of literal
values.

A jagged array is initialized with two square brackets [][].

Array and arraylist ;


The main differences between Array and ArrayList in C# are: Array is fixed size,
whereas ArrayList is dynamically sized. Array can only store items of a single,
specified type, whereas ArrayList can store items of any type.

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.

13 | P a g e
A method represents a particular behavior. It performs some action and might return
information about an object, or update an object’s data.

Why use methods? To reuse code: define the code once, and use it many times…

The Main() Method ;

The Main() method is an entry point of console and windows applications


on the .NET or .NET Core platform. It is also an entry of ASP.NET Core web
applications.

When you run an application, it starts the execution from the Main() method. So, a
program can have only one Main() method as an entry point. However, a class can
have multiple Main() methods, but any one of them can be an entry point of an
application.

Parameters and Arguments


Information can be passed to methods as parameter. Parameters act as variables inside the
method.

They are specified after the method name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma.

Default Parameter Value


You can also use a default parameter value, by using the equals sign (=).

static void MyMethod(string country = "Norway")

Console.WriteLine(country);

Return Values
In the previous page, we used the void keyword in all examples, which indicates that the
method should not return a value.

If you want the method to return a value, you can use a primitive data type (such
as int or double) instead of void, and use the return keyword inside the method:

Named Arguments
14 | P a g e
It is also possible to send arguments with the key: value syntax.

Classes
A class is a user-defined blueprint or prototype from which objects are created.
A class can contain one or more constructors, fields, methods, properties,
delegates, and events. They are called class members. A class and its members
can have access modifiers such as public, private, protected, and internal, to
restrict access from other parts of the program.

Basically, a class combines the fields and methods(member function which defines
actions) into a single unit. In C#, classes support polymorphism, inheritance and
also provide the concept of derived classes and base classes.

Classes and objects are the two main aspects of object-oriented programming.

Objects
Objects are instances of the class that holds different data in properties/fields
and can interact with other objects.

An object is basically a block of memory that has been allocated and configured
according to the blueprint.

Class Members
Fields and methods inside classes are often referred to as "Class Members":

Access Modifiers
public: Accessible from anywhere.
private: Accessible only within the same class.
protected: Accessible within the same class and subclasses.
internal: Accessible only within the same assembly.

Why Access Modifiers?


To control the visibility of class members (the security level of each individual class and class
member).

15 | P a g e
To achieve "Encapsulation" - which is the process of making sure that "sensitive" data is
hidden from users. This is done by declaring fields as private. You will learn more about this in
the next chapter.

Properties
Properties hold the data temporarily during the execution of an application.

A property is like a combination of a variable and a method, and it has two methods:
a get and a set method:

The get method returns the value of the variable name.

The set method assigns a value to the name variable. The value keyword represents the
value we assign to the property.

Accessors :

Accessors are known as the getting and Set portions of a property.

Enums
An enum is a special "class" that represents a group
of constants (unchangeable/read-only variables).

To create an enum, use the enum keyword (instead of class or interface), and
separate the enum items with a comma:

Enum is short for "enumerations", which means "specifically listed"


Ex ;
enum WeekDays
{
Monday,Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}

Working With Files


The File class from the System.IO namespace, allows us to work with files:

16 | P a g e
Exceptions
When executing C# code, different errors can occur: coding errors made by the programmer,
errors due to wrong input, or other unforeseeable things.

.NET includes built-in exception classes for every possible error.


The Exception class is the base class of all the exception classes.

When an error occurs, C# will normally stop and generate an error message. The technical
term for this is: C# will throw an exception (throw an error).

Exception Handling
exception handling in C# using try, catch, and finally blocks.

Exceptions in the application must be handled to prevent crashing of the program and
unexpected result, log exceptions and continue with other functionalities. C# provides
built-in support to handle the exception using try, catch & finally blocks.

Try and catch


The try statement allows you to define a block of code to be tested for errors while it is
being executed.

The catch statement allows you to define a block of code to be executed, if an error occurs
in the try block.

Finally
The finally statement lets you execute code, after try...catch, regardless of the result:

The throw keyword


The throw statement allows you to create a custom error.

The throw statement is used together with an exception class. There are many exception classes
available in
C#: ArithmeticException, FileNotFoundException, IndexOutOfRangeException, TimeOutException,
etc:

An exception can be raised manually by using the throw keyword. Any type of exceptions which
is derived from Exception class can be raised using the throw keyword.

17 | P a g e
Custom exceptions
Custom exceptions are a powerful feature of . NET C# that allows you to handle errors
and unexpected situations in your application in a more specific way.

IndexOutOfRangeException

An IndexOutOfRangeException exception is thrown when an invalid index is used to


access a member of an array or a collection, or to read or write from a particular location
in a buffer. This exception inherits from the Exception class but adds no unique members.

NullReferenceException
A NullReferenceException exception is thrown when you try to access a member on a
type whose value is null. A NullReferenceException exception typically reflects developer
error and is thrown in the following scenarios: You've forgotten to instantiate a reference
type.

Interface
In the human world, a contract between the two or more humans binds them to act as per
the contract. In the same way, an interface includes the declarations of related
functionalities. The entities that implement the interface must provide the implementation
of declared functionalities.

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.

1. Interface can contain declarations of method, properties, indexers, and events.


2. Interface cannot include private, protected, or internal members. All the
members are public by default.
3. Interface cannot contain fields, and auto-implemented properties.
4. A class or a struct can implement one or more interfaces implicitly or explicitly.
Use public modifier when implementing interface implicitly, whereas don't use
it in case of explicit implementation.
5. Implement interface explicitly using InterfaceName.MemberName.

6. An interface can inherit one or more interfaces.


A class or a Struct can implement one or more interfaces using colon :.
Interface members must be implemented with the public modifier; otherwise, the compiler will
give compile-time errors.

18 | P a g e
Partial Classes and Methods
In C#, you can split the implementation of a class, a struct, a method, or an
interface in multiple .cs files using the partial keyword. The compiler will combine all
the implementation from multiple .cs files when the program is compiled.

USE :

the help of partial classes, we can split our classes into multiple files

Rules for Partial Classes


• All the partial class definitions must be in the same assembly and namespace.
• All the parts must have the same accessibility like public or private, etc.
• If any part is declared abstract, sealed or base type then the whole class is
declared of the same type.
• Different parts can have different base types and so the final class will inherit
all the base types.
• The Partial modifier can only appear immediately before the
keywords class, struct, or interface.
• Nested partial types are allowed.

Rules for Partial Methods


• Partial methods must use the partial keyword and must return void.
• Partial methods can have in or ref but not out parameters.
• Partial methods are implicitly private methods, so cannot be virtual.
• Partial methods can be static methods.
• Partial methods can be generic.

Static Class, Methods, Constructors, Fields


static means something which cannot be instantiated. You cannot create an
object of a static class and cannot access static members using an object.

Static classes in C# cannot be instantiated and are limited to static members


only, making them sealed and inaccessible for inheritance.
Rules for Static Methods ;
Static methods can be defined using the static keyword before a return type and after an
access modifier. Static methods can be overloaded but cannot be overridden. Static
methods can contain local static variables. Static methods cannot access or call non-static
variables unless they are explicitly passed as parameters.

19 | P a g e
Static constructors have the following properties:

• A static constructor doesn't take access modifiers or have parameters.


• A class or struct can only have one static constructor.
• Static constructors cannot be inherited or overloaded.

Indexers ;
Indexers allow instances of a class or struct to be indexed just like arrays.

An indexer is a special type of property that allows a class or a structure to be


accessed like an array for its internal collection. C# allows us to define custom
indexers, generic indexers, and also overload indexers.

An indexer can be defined the same way as property with this keyword and square
brackets [].

public string this[int index]


{

Note:
Indexer does not allow ref and out paramters.

Generics
generic means not specific to a particular data type.

C# allows you to define generic classes, interfaces, abstract classes, fields,


methods, static methods, properties, events, delegates, and operators using
the type parameter and without the specific data type. A type parameter is a
placeholder for a particular type specified when creating an instance of the generic
type.

USE :

Use generic types to maximize code reuse, type safety, and performance. The most
common use of generics is to create collection classes. The . NET class library
contains several generic collection classes in the System

20 | P a g e
Define Generic Class
class DataStore<T>
{
public T Data { get; set; }
}

A generic type is declared by specifying a type parameter in an angle brackets after


a type name, e.g. TypeName<T> where T is a type parameter.

Generic Class Characteristics


• A generic class increases the reusability. The more type parameters mean more
reusable it becomes. However, too much generalization makes code difficult to
understand and maintain.
• A generic class can be a base class to other generic or non-generic classes or
abstract classes.
• A generic class can be derived from other generic or non-generic interfaces,
classes, or abstract classes.

Advantages of Generics
1. Generics increase the reusability of the code. You don't need to write code to
handle different data types.
2. Generics are type-safe. You get compile-time errors if you try to use a different
data type than the one specified in the definition.
3. Generic has a performance advantage because it removes the possibilities of
boxing and unboxing.

Generic & Non-generic Collections


C# includes specialized classes that store series of values or objects are called
collections.

• List: In Generic List, we have to specify a data type to its contents, and all elements will have the
same datatype. ...
• Dictionary , Sorted List , Stack: ...
• Queue , ArrayList , HashTable ,Sorted List:

There are two types of collections available in C#: non-generic collections and generic collections.

The System.Collections namespace contains the non-generic collection types


and System.Collections.Generic namespace includes generic collection types.

In most cases, it is recommended to use the generic collections because they perform faster than
non-generic collections and also minimize exceptions by giving compile-time errors.

21 | P a g e
Tuple
The Tuple<T> class was introduced in .NET Framework 4.0. A tuple is a data structure that
contains a sequence of elements of different data types. It can be used where you want
to have a data structure to hold an object with properties, but you don't want to create a
separate type for it.

Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>

USES ;

Tuples in C# are utilized for returning multiple values from methods, passing multiple values as a single
parameter, and temporary storage without defining a separate class.

Tuple Limitations:
Tuples in C# are reference types, allocated on the heap, potentially leading to CPU-intensive
operations; limited to eight elements and require nested tuples for additional elements,
risking ambiguity; accessed via properties with naming patterns like
Item<elementNumber>, which might not be intuitive.

Delegates
What if we want to pass a function as a parameter? How does C# handles the
callback functions or event handler? The answer is - delegate.

The delegate is a reference type data type that defines the method signature. You can
define variables of delegate, just like other data type, that can refer to any method with
the same signature as the delegate.

There are three steps involved while working with delegates:

1. Declare a delegate
2. Create an instance and reference a method
3. Invoke a delegate

Example: Declare a Delegate


public delegate void MyDelegate(string msg);

1. Delegate is the reference type data type that defines the signature.
2. Delegate type variable can refer to any method with the same signature as the
delegate.
3. Delegate is used to declare an event and anonymous methods in C#.

22 | P a g e
“Delegates allow methods to be passed as parameters. Delegates can be used to
define callback methods.”

Delegates can be chained together; for example, multiple methods can be called on
a single event. Methods don't have to match the delegate type exactly.

Func Delegate
The Func delegate that takes one input parameter and one out parameter is defined in
the System namespace
namespace System
{
public delegate TResult Func<in T, out TResult>(T arg);
}
1. Func is built-in delegate type.
2. Func delegate type must return a value.
3. Func delegate type can have zero to 16 input parameters.
4. Func delegate does not allow ref and out parameters.
5. Func delegate type can be used with an anonymous method or lambda expression.
Action Delegate

Action is a delegate type defined in the System namespace. An Action type delegate
is the same as Func delegate except that the Action delegate doesn't return a value.
In other words, an Action delegate can be used with a method that has a void return
type.

Advantages of Action and Func Delegates


1. Easy and quick to define delegates.
2. Makes code short.
3. Compatible type throughout the application.

Predicate Delegate
Predicate delegate takes one input parameter and boolean return type.

Anonymous method and Lambda expression can be assigned to the predicate delegate.

23 | P a g e
Anonymous Method
1. Anonymous method can be defined using the delegate keyword
2. Anonymous method must be assigned to a delegate.
3. Anonymous method can access outer variables or functions.
4. Anonymous method can be passed as a parameter.
5. Anonymous method can be used as event handlers.

Events
“Events enable a class or object to notify other classes or objects when
something of interest occurs.

The class that sends (or raises) the event is called the publisher and the classes
that receive (or handle) the event are called subscribers.”

An event is a wrapper around a delegate. It depends on the delegate.

Use "event" keyword with delegate type variable to declare an event.

1. Use built-in delegate EventHandler or EventHandler<TEventArgs> for


common events.
2. The publisher class raises an event, and the subscriber class registers for an
event and provides the event-handler method.
3. Name the method which raises an event prefixed with "On" with the event
name.
1. The signature of the handler method must match the delegate signature.

Delegate Event
A delegate is declared using the delegate keyword. An event is declared using the event
keyword.

Delegate is a function pointer. It holds the reference The event is a notification mechanism
of one or more methods at runtime. that depends on delegates

24 | P a g e
Covariance and Contravariance in C#
Covariance and contravariance allow us to be flexible when dealing with class
hierarchy.

Covariance enables you to pass a derived type where a base type is expected. Co -
variance is like variance of the same kind.

Contravariance is applied to parameters. Contravariance allows a method with


the parameter of a base class to be assigned to a delegate that expects the
parameter of a derived class.

Example: Class Hierarchy


public class Small
{

}
public class Big: Small
{

}
public class Bigger : Big
{

Extension Method

Extension methods are a powerful feature in C# that allows you to add new functionality to
existing types without modifying their source code.
Points to Remember :

1. Extension methods are additional custom methods which were originally not included
with the class.
2. Extension methods can be added to custom, .NET Framework or third party classes,
structs or interfaces.
3. The first parameter of the extension method must be of the type for which the
extension method is applicable, preceded by the this keyword.
4. Extension methods can be used anywhere in the application by including the
namespace of the extension method.

25 | P a g e
Stream
C# includes following standard IO (Input/Output) classes to read/write from
different sources like files, memory, network, isolated storage, etc.

Stream: System.IO.Stream is an abstract class that provides standard methods to


transfer bytes (read, write, etc.) to the source. It is like a wrapper class to transfer
bytes. Classes that need to read/write bytes from a particular source must
implement the Stream class.

The following classes inherit Stream class to provide the functionality to Read/Write
bytes from a particular source:

FileStream reads or writes bytes from/to a physical file, whether it is a .txt, .exe,
.jpg, or any other file. FileStream is derived from the Stream class.

MemoryStream: MemoryStream reads or writes bytes that are stored in memory.

BufferedStream: BufferedStream reads or writes bytes from other Streams to


improve certain I/O operations' performance.

NetworkStream: NetworkStream reads or writes bytes from a network socket.

PipeStream: PipeStream reads or writes bytes from different processes.

CryptoStream: CryptoStream is for linking data streams to cryptographic


transformations.

Working with Files & Directories


C# provides the following classes to work with the File system. They can be used
to access directories, access files, open files for reading or writing, create a new file
or move existing files from one location to another, etc.

File
C# includes static File class to perform I/O operation on physical file system. The
static File class includes various utility method to interact with physical file of any
type e.g. binary, text etc.

Points to Remember :

1. File is a static class to read\write from physical file with less coding.

26 | P a g e
2. Static File class provides functionalities such as create, read\write, copy, move, delete
and others for physical files.
3. Static Directory class provides functionalities such as create, copy, move, delete etc
for physical directories with less coding.
4. FileInfo and DirectoryInfo class provides same functionality as static File and Directory
class.
Thus you can use FileInfo, StreamReader and StreamWriter class to read/write
contents from physical file.

Object Initializer Syntax


C# 3.0 (.NET 3.5) introduced Object Initializer Syntax, a new way to initialize an
object of a class or collection. Object initializers allow you to assign values to the
fields or properties at the time of creating an object without invoking a constructor.

Collection initializer Syntax


IList<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName =
"John"} ,
null
};

Advantages of Initializers

• Initializer syntax makes a code more readable, easy to add elements into the
collection.
• Useful in multi-threading.

Design Principle
SOLID design principles in C# are basic design principles. SOLID stands
for Single Responsibility Principle (SRP), Open closed Principle (OSP), Liskov
substitution Principle (LSP), Interface Segregation Principle (ISP), and
Dependency Inversion Principle (DIP).

Design Pattern
Design Pattern provides low-level solutions related to implementation, of commonly
occurring object-oriented problems. In other words, design pattern suggests a specific
implementation for the specific object-oriented programming problem.

27 | P a g e
For example, if you want to create a class that can only have one object at a time,
then you can use the Singleton design pattern which suggests the best way to create a
class that can only have one object.

Design patterns are tested by others and are safe to follow, e.g. Gang of Four patterns:
Abstract Factory, Factory, Singleton, Command, etc.

How to calculate the code execution time

As a programmer, we may need to find out the execution time used by a particular
segment of the C# code, in order to optimize the performance. For example, we may
want to know how much time is taken for reading multiple files in the file system, or
fetching data from the database, or executing some business logic.

How to read file using StreamReader

Visit Stream I/O to know more about Stream class heirarchy.

Use the StreamReader class to read a physical file in C#.

Difference between Hashtable and Dictionary

Hashtable Dictionary
Hashtable is included in Dictionary is included in
the System.Collections namespace the System.Collections.Generic namespace
. .
Hashtable is a loosely typed (non- Dictionary is a generic collection. So it can
generic) collection, this means it store key-value pairs of specific data types.
stores key-value pairs of any data
types.
Hashtable is thread safe. Only public static members are thread safe
in Dictionary.
Hashtables and Dictionaries are two commonly used
collection type for storing and retrieving key-value pairs.

28 | P a g e
Object Oriented Programming

OOP stands for Object-Oriented Programming.

Object Oriented Programming in C#


Object-oriented programming is a way of developing software applications using real-world
terminologies to create entities that interact with one another using objects.

Object-oriented programming makes applications flexible (easy to change or add new


features), reusable, well-structured, and easy to debug and test.

Most programming languages provide the following basic building blocks to build object -
oriented applications:

Classes, method, Properties, Objects, interfaces.

several advantages over procedural programming:

• OOP is faster and easier to execute


• OOP provides a clear structure for the programs
• OOP helps to keep the C# code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug
• OOP makes it possible to create full reusable applications with less code and shorter
development time

Constructors
A constructor is a special method that is used to initialize objects.

the constructor name must match the class name, and it cannot have a return
type (like void or int).

Also note that the constructor is called when the object is created.

All classes have constructors by default: if you do not create a class constructor yourself, C#
creates one for you. However, then you are not able to set initial values for fields.

The use of Private Constructor in C#.

It is used to pause the object curation of a class. This is used in Singleton Class. It can be used to stop a
class from being inherited.

29 | P a g e
Destructor?

A Destructor is used to free the dynamically allocated memory and release the resources.
It is instantly invoked when the Object is destroyed.

Namespaces.

It allows the creation of a system to organize the code.

Object-oriented Design Principles


There are various object-oriented principles and techniques using which you can develop
applications that are maintainable and extendable.

The followings are four main principles of object-oriented programming:

1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism

Abstraction
Abstract Classes and Methods
“Show only necessary things”
abstraction is the process of hiding certain details and showing only essential
information to the user.
Abstraction can be achieved with either abstract classes or interfaces

The abstract keyword is used for classes and methods:

Abstract class: is a restricted class that cannot be used to create


objects (to access it, it must be inherited from another class).

Abstract method: can only be used in an abstract class, and it does not
have a body. The body is provided by the derived class (inherited from).

Why And When To Use Abstract Classes and Methods?

To achieve security - hide certain details and only show the important
details of an object.
30 | P a g e
---------------------------------------------------------------------

Interfaces ;
Another way to achieve abstraction in C#, is with interfaces.

An interface is a completely "abstract class", which can only contain abstract methods
and properties (with empty bodies):

By default, members of an interface are abstract and public.

Note: Interfaces can contain properties and methods, but not fields.

Notes on Interfaces:

• Like abstract classes, interfaces cannot be used to create objects (in the example
above, it is not possible to create an "IAnimal" object in the Program class)
• Interface methods do not have a body - the body is provided by the "implement"
class
• On implementation of an interface, you must override all of its methods
• Interfaces can contain properties and methods, but not fields/variables
• Interface members are by default abstract and public
• An interface cannot contain a constructor (as it cannot be used to create objects)

Why And When To Use Interfaces?

1) To achieve security - hide certain details and only show the important details of an
object (interface).

2) C# does not support "multiple inheritance" (a class can only inherit from one base
class). However, it can be achieved with interfaces, because the class
can implement multiple interfaces. Note: To implement multiple interfaces, separate
them with a comma (see example below).

Implicit Interface Implementation.

This is the most common way to implement the members of an interface. In this one, one
doesn’t have to specify the interface name of the members and implement the implicity.

Explicit Interface Implementation.

An explicit interface implementation doesn't have an access modifier since it isn't


accessible as a member of the type it's defined in. Instead, it's only accessible when
called through an instance of the interface.

31 | P a g e
Encapsulation
”Hides the Complexity “

Encapsulation is known as wrapping, also considered as hiding properties and


methods. It is utilized for hiding the code and data in one unit to cover the
data from the outside world. For Encapsulation, the best example is Class.

Encapsulation is a fundamental concept of object-oriented in programming


language.encapsulation is a technique to implement abstraction .

It refers to the bundling of data and related operations in a single unit or


object. Encapsulation is achieved through the use of classes and access
modifiers such as public,private, and producted.

The meaning of Encapsulation is to make sure that "sensitive" data is


hidden from users. To achieve this, you must:

• declare fields/variables as private


• provide public get and set methods, through properties, to access and
update the value of a private field

Advantages of Encapsulation:
• Hides data and complexities.
• Restrict unauthorized access of data by allowing authorization before data
access.
• Allow validation before setting data.
• Only the author of the class needs to understand the implementation, not
others.
• Makes applications easy to maintain.
• Fields can be made read-only (if you only use the get method),
or write-only (if you only use the set method)
• Flexible: the programmer can change one part of the code without
affecting other parts
• Increased security of data

32 | P a g e
Class Relations:
In object-oriented programming, classes interact with each other to accomplish one or
more features of an application..

There are three types of relationships in object-oriented programming based on how a


class interacts with another class.

1. Association
2. Composition
o Composition
o Aggregation
3. Inheritance

Association
Association relationship is referred to as "uses a" relationship where a class uses
another class to perform some operation.

• A class only uses behaviors/functionalities (methods) of another class but does not
change them by overriding them.
• A class does not inherit another class.
• A class does not include (own) another class as a public member.

Composition
Composition is referred to as "has a" relationship. Composition relationship is formed
when a class has a reference to another class as an instance property.

• A class (parent) contains a reference to another class (child).


• The child class doesn't exist without the parent class.
• Deleting the parent class will also delete the child class
• A class can also include a reference of the id property of another class.

Aggregation ;
• Aggregation is another type of composition ("has a" relation).
• A class (parent) contains a reference to another class (child) where both classes can
exist independently.
• A class can also include a reference of the id property of another class

Inheritance :
“ Parent and child class relationship ”

Inheritance is one of the fundamental attribute of OOPs.

33 | P a g e
Inheritance is another type of relationship between classes. Inheritance is a mechanism
of reusing the functionalities of one class into another related class.

it is possible to inherit fields and methods from one class to another. We group the
"inheritance concept" into two categories:

• Derived Class (child) - the class that inherits from another class
• Base Class (parent) - the class being inherited from

To inherit from a class, use the : symbol.

In the example below, the Car class (child) inherits the fields and methods from
the Vehicle class (parent):

Why And When To Use "Inheritance"?

- It is useful for code reusability: reuse fields and methods of an existing class when you
create a new class.

Important Points:
• In C#, three types can participate in inheritance: Class, Struct, and Interface.
• A class can inherit a single class only. It cannot inherit from multiple classes.
• A class cannot inherit from a struct.
• A class can inherit (implement) one or more interfaces.
• A Struct can inherit from one or more interfaces. However, it cannot inherit from
another struct or class.
• An interface can inherit from one or more interfaces but cannot inherit from a class or
a struct.
• Constructors or destructors cannot be inherited.

The sealed Keyword


If you don't want other classes to inherit from a class, use the sealed keyword:

Polymorphism
34 | P a g e
Polymorphism is a Greek word that means multiple forms or shapes.

Polymorphism means "many forms" .We can use polymorphism if you want to have multiple
forms of one or more methods of a class with the same name.

For example, think of a base class called Animal that has a method called animalSound().
Derived classes of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own
implementation of an animal sound (the pig oinks, and the cat meows, etc.):

Why And When To Use "Inheritance" and "Polymorphism"?

- It is useful for code reusability: reuse fields and methods of an existing class when you
create a new class.

In C#, polymorphism can be achieved in two ways:

1. Compile-time Polymorphism
2. Run-time Polymorphism

Compile-time Polymorphism (Method Overloading)


Compile-time polymorphism is also known as method overloading. C# allows us to define
more than one method with the same name but with different signatures. This is called
method overloading.

Rules for Method Overloading:

1. Method names should be the same but method signatures must be different. Either
the number of parameters, type of parameters, or order of parameters must be
different.
2. The return type of the methods does not play any role in the method overloading.
3. Optional Parameters take precedence over implicit type conversion when deciding
which method definition to bind.

Runtime Polymorphism: Method Overriding


Run-time polymorphism is also known as inheritance-based polymorphism or method
overriding.

Inheritance lets derived classes inherit base class members, enabling method overriding
for redefining behavior, known as runtime polymorphism.

However, C# provides an option to override the base class method, by adding


the virtual keyword to the method inside the base class, and by using
the override keyword for each derived class methods:

Virtual?

35 | P a g e
One uses Virtual to modify a method/property/indexer or event declared in the base
class. It allows it to be overridden in the specific derived Class.

Rules for Overriding:


• A method, property, indexer, or event can be overridden in the derived class.
• Static methods cannot be overridden.
• Must use virtual keyword in the base class methods to indicate that the methods can
be overridden.
• Must use the override keyword in the derived class to override the base class method.

Method Hiding
The method of hiding the base class's methods from the derived class is known as
Method Hiding. This method is also known as Method Shadowing. The
implementation of the methods of a base class can be hidden from the derived
class in method hiding using the new keyword.

SOLID Principles in C#
In object-oriented programming, SOLID is an acronym for the five design principles
introduced by Robert C. Martin. These principles are used to design software applications
maintainable and testable.

SOLID are principles, not patterns. Learn what's the difference between pattern and
principle.

SOLID stands for:

• S = Single Responsibility Principle


• O = Open/Closed Principle
• L = Liskov Substitution Principle
• I = Interface Segregation Principle
• D = Dependency Inversion Principle

Single Responsibility Principle


The Single Responsibility Principle is the first principle of SOLID principles. It is the
fundamental principle of object-oriented programming that determines how we should design
classes.

Each software module should have one and only one reason to change.

Open/Closed Principle
The Open/Closed Principle (OCP) is the second principle of SOLID.

36 | P a g e
Software entities (classes, modules, functions, etc.) should be open for extension, but closed for
modification.

Liskov Substitution Principle


Subtypes must be substitutable for their base type.

Interface Segregation Principle


Clients should not be forced to depend on methods they do not use.

Dependency Inversion Principle


Dependency Inversion Principle is the last principle of SOLID principles. It helps in loose coupling.

High-level modules should not depend on low-level modules. Both should depend on abstraction.

Design Patterns
Design pattern in software engineering is a general, reusable solution to a commonly
occurring problem in software design.

Developers face some problems while developing applications or in the software


application Lifecycle which are common and repeated, for example, creation and disposal
of objects, interaction between objects, the structure of classes that enhance cohesion and
loose coupling, fixing of bugs in a way that minimize changing of source codes, etc.

How to use design patterns?

We can use one design pattern or a combination of design patterns to solve a problem in your
software application.

A design pattern suggests a specific implementation for the specific object-oriented programming
problem.

State the types of Design Patterns.

There are three types of Design Patterns-

Creational Patterns: It deals with the creation of Objects and Classes.

Structural Patterns: It deals with Class and Object Composition.

Behavioral Patterns- It deals with Class and Object Communication.

37 | P a g e
Singleton
The singleton design pattern is a creational design pattern.

Singleton design pattern in c# has just one instance that gives global access to it.Access of one
instance is preferred to avoid unexpected results.

Singleton Class Structure


A class should have the following structure for singleton pattern:

• Should have a private or protected constructor. No public and parameterized constructors.


• Should have a static property (with a private backing field) to return an instance of a class. A
static method can also be used to return an instance.
• At least have one non-static public method for a singleton operation.

Abstract Factory Definition


The Abstract Factory design pattern is a creational pattern that provides an interface for creating
families of related or dependent objects without specifying their concrete classes. It allows the
client code to create objects of different types that belong to the same family.

Factory method pattern

Factory method pattern is a creational design pattern that provides an interface for creating
objects but allows subclasses to decide which class to instantiate. By using this pattern, you can
encapsulate object creation logic in a separate method of a subclass.

Difference between Struct and Class :

a struct is a value type while a class is a reference type.


Value types contain their data directly on the stack, while reference types store a
reference to an object containing the data on the heap.

This difference is important because it affects how the objects are copied and passed
around in memory.
Difference between abstract and interface
an Interface provides only those public services declared in the interface, whereas an
abstract class provides the public services defined in an abstract class and those
members that are inherited from the abstract class's base class.

38 | P a g e
Readonly
• Readonly is known as “readonly” keyword in C#.
• It is also known immutable values.
• They are known at compile and run time and do not change their values at run
time like in any function for the life of application till the application is running.
• You can assay their value by constructor when we call constructor with “new”
keyword.

39 | P a g e
.NET Core
The full name of the . NET Core is Network Enabled Technologies Core.

The abbreviation ASP.NET Core stands for Active Server Pages Network Enabled
Technologies Core.

Overview ;
• .NET Core is a new version of .NET Framework, which is a free, open-
source, general-purpose development platform maintained by Microsoft.
It is a cross-platform framework that runs on Windows, macOS, and
Linux operating systems.
• .NET Core Framework can be used to build different types of applications
such as mobile, desktop, web, cloud, IoT, machine learning,
microservices, game, etc.
• .NET Core is written from scratch to make it modular, lightweight, fast,
and cross-platform Framework. It includes the core features that are
required to run a basic .NET Core app.
• Other features are provided as NuGet packages, which you can add it in
your application as needed. In this way, the .NET Core application speed
up the performance, reduce the memory footprint and becomes easy to
maintain.

Why .NET Core?


.NET Core addresses limitations of the .NET Framework by being open-source, cross-
platform, and versatile, enabling development for various devices and environments
with a unified framework.

NET Core is its cross-platform support. Developers can write and deploy . NET Core applications on
multiple operating systems such as Windows, macOS, and Linux.

.NET Core version history:


1.0 (2016), 2.0 (2017), 3.0 (2019), 3.1 (2019, LTS), 5 (2020), 6 (2021).

The name .NET Core was changed after .NET Core 3.1. The next version of .NET Core after
version 3.1 was named .NET 5. The latest version of .NET Core is .NET 7 as of this writing.

40 | P a g e
.NET 5 unifies the previously separate .NET Core, .NET Framework, and Xamarin platforms,
making it easier for developers to use a single platform for various application types.

.NET Core Characteristics:

1. Cross-platform compatibility.
2. Open-source development.
3. High performance.
4. Modular design.
5. Versatility for various application types.
6. Continuous evolution and updates.
7. Containerization support.
8. Cloud-native capabilities.
9. Simplified deployment process.
10. Enhanced security features.

ASP.NET Core ;
ASP.NET Core is the new and totally re-written version of the ASP.NET web framework. It
is a free, open-source, and cross-platform framework for building cloud-based
applications, such as web apps, IoT apps, and mobile backends. It is designed to run on
the cloud as well as on-premises.

Same as .NET Core, it was architected modular with minimum overhead, and then other
more advanced features can be added as NuGet packages as per application requirement.

This results in high performance, require less memory, less deployment size, and easy
to maintain.

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.

ASP.NET Core Version History

ASP.NET Core was introduced in 2016, offering cross-platform capabilities and improved
performance compared to traditional ASP.NET.

ASP.NET 5 onwards, it's unified under the ASP.NET Core framework, retaining its
advantages while accommodating all types of applications.

41 | P a g e
.NET Core can be installed in two ways:

1. By installing Visual Studio 2022


2. By installing .NET Core SDK (Software Development Kit)

ASP.NET Core MVC Project Structure


We created the ASP.NET Core MVC application. The following is a default project structure
of the ASP.NET Core MVC application in Visual Studio.

Command-Line Interface ;
The . NET command-line interface (CLI) is a cross-platform toolchain for developing,
building, running, and publishing . NET applications.

The .NET Core CLI is installed with .NET Core SDK for selected platforms. So we don't
need to install it separately on the development machine.

Examples;
• macOS: Mac Terminal.
• Windows: Command Prompt.
• Linux: Linux Bash Shell.
• Google Cloud Platform: PowerShell, Cloud Shell.
• Amazon Web Services: AWS Command Prompt.
• Microsoft Azure: Azure CLI Bash.

42 | P a g e
The Common Language Runtime ;
(CLR) is programming that manages the execution of programs written in any of
several supported languages, allowing them to share common object-oriented
classes written in any of the languages. It is a part of Microsoft's . NET Framework.
The CLR manages the allocation and deallocation of memory for objects and
performs garbage collection to reclaim unused memory.

The runtime provides the following benefits:


• Performance improvements.
• The ability to easily use components developed in other languages.
• Extensible types provided by a class library.
• Language features such as inheritance, interfaces, and overloading for object-
oriented programming.

Dependency Injection
• Dependency Injection is a software development and design pattern that
helps in eliminating the dependency of one class on the other class.
• The purpose of DI is to promote code modularity, reusability and testability.
• ASP.NET Core supports the dependency injection (DI) software design
pattern, which is a technique for achieving Inversion of Control (IoC) between
classes and their dependencies.
• specific to dependency injection within MVC controllers, see Dependency
injection into controllers in ASP.NET Core.
• Dependency injection (DI) is a design pattern widely used in software
development, and understanding it is a basic requirement for anyone wanting
to work with web development in ASP.NET Core.
The use of dependency injection?
Dependency injections are useful to create loosely coupled programs, while also
following the SOLID software design principles.
Real life example ;

Sending emails:

Imagine an EmailService class responsible for sending emails. Traditionally, it might


directly create an EmailSender object (dependency) within its constructor.
For example, a Car class might need a reference to an Engine class.

43 | P a g e
Which method is used for dependency injection?

There are three types of dependency injection — constructor injection, method injection,
and property injection.
Built-in IoC Container
ASP.NET Core comes with a basic built-in IoC (Inversion of Control) container.
While it supports constructor injection and manages services, it lacks advanced
features found in third-party containers.
If you need features like auto-registration or interceptors, you can replace it with a
third-party container.

ASP.NET Core framework includes built-in IoC container for automatic dependency
injection. The built-in IoC container is a simple yet effective container. Let's
understand how the built-in IoC container works internally.

The followings are important interfaces and classes for built-in IoC container:

Interfaces:

1. IServiceProvider
2. IServiceCollection

Classes:

1. ServiceProvider
2. ServiceCollection
3. ServiceDescription
4. ServiceCollectionServiceExtensions
5. ServiceCollectionContainerBuilderExtensions

There are basically two types of services in ASP.NET Core:

1. Framework Services: Services which are a part of ASP.NET Core framework such as
IApplicationBuilder, IHostingEnvironment, ILoggerFactory etc.
2. Application Services: The services (custom types or classes) which you as a
programmer create for your application.

Constructor Injection
Once we register a service, the IoC container automatically performs constructor injection
if a service type is included as a parameter in a constructor.

For example, we can use ILog service type in any MVC controller.

44 | P a g e
Action Method Injection

Sometimes we may only need dependency service type in a single action method. For this,
use [FromServices] attribute with the service type parameter in the method.

Property Injection
Built-in IoC container does not support property injection. You will have to use third party
IoC container.

Middleware ;
ASP.NET Core introduced a new concept called Middleware. A middleware is
nothing but a component (class) which is executed on every request in ASP.NET
Core application.

Uses;

Middleware is a powerful tool in . NET Core that allows you to modify incoming
requests and outgoing responses. It can be used to perform a wide range of tasks
such as authentication, logging, compression, and caching. In addition to the built-in
middleware components that are available in

Work ;

The architecture of Middleware in ASP.NET Core consists of a pipeline of


components that handle incoming HTTP requests and outgoing responses.

In the classic ASP.NET, HttpHandlers and HttpModules were part of request


pipeline. Middleware is similar to HttpHandlers and HttpModules where both needs
to be configured and executed in each request.

In ASP.NET Core web applications, the order of middleware execution in the request
pipeline is determined by the sequence in which they are added, allowing for each
middleware to modify HTTP requests and responses and pass control to the next
component.

Add Custom Middleware ;


In the ASP.NET Core Web API, middleware is a component that sits in the request pipeline
and processes HTTP requests and responses. It allows you to add custom logic to handle
various aspects of the request/response flow, such as authentication, logging, error
handling, and more.

45 | P a g e
Configure the Default File to be Served on the Root Request

As we learned in the Set Default File section, app.UseDefaultFiles() middleware serves


the following files on the root request.

1. Default.html
2. Default.htm
3. Index.html
4. Index.htm

Environment Variable ;

ASP.NET Core uses the Environment Variable called ASPNETCORE_ENVIRONMENT,


which indicates the runtime environment. The value of this variable may be something as
per the requirement but usually be a Production, Staging, and Development.

Exception Handling
Exception handling is one of the most important features of any application. Fortunately,
ASP.NET Core includes a middleware that makes exception handling easy.

exception handling involves catching exceptions that occur during the processing of
requests and returning appropriate error responses to the clients

How many ways can you handle exceptions in .NET Core?


In this article I will try to explain various easy ways to handle exceptions:
1. Try Catch block.
2. In Built middleware.
3. Custom Middleware.
4. Exception Filter.
Install Microsoft.AspNetCore.Diagnostics Package

To handle exceptions and display user friendly messages, we need to


install Microsoft.AspNetCore.Diagnostics NuGet package and add middleware in
the Configure() method.

The Microsoft.AspNetCore.Diagnostics package includes following extension methods to handle


exceptions in different scenario:

1. UseDeveloperExceptionPage ;

The major purpose of UseDeveloperExceptionPage() is to help the user to inspect


exception details during the development phase.

46 | P a g e
2. UseExceptionHandler ;

UseExceptionHandler is a middleware method that is used to handle exceptions that


are thrown during the processing of an HTTP request in an ASP.NET Core
application.

Serving Static Files


Static files, such as HTML, CSS, images, and JavaScript, are assets an ASP.NET Core
app serves directly to clients by default.

Static files are typically located in the web root (wwwroot) folder.

ASP.NET Core application cannot serve static files by default. We must


include Microsoft.AspNetCore.StaticFiles middleware in the request pipeline.

Logging in .NET Core


.NET supports high performance, structured logging via the ILogger API to help monitor
application behavior and diagnose issues.

“Logging is the process of recording events in software as they happen in real-


time, along with other information such as the infrastructure details, time taken
to execute, etc. Logging is an essential part of any software application”.
Logs can be written to different destinations by configuring different logging providers.

It helps debug issues, monitor the application's health, and understand user
behavior.
Why need logging?

Logging keeps track of what happens while a program is running, including any errors,
warnings, or notable events that occur

How does logging work in .NET core?


Basics of the . NET Core Logging With LoggerFactory. It is designed as a logging API
that developers can use to capture built-in ASP.NET logging as well as for their own
custom logging. The logging API supports multiple output providers and is extensible to
potentially be able to send your application logging anywhere.

Logging in ASP.NET Core ;

47 | P a g e
Logging is the process of recording events in software as they happen in real-time, along
with other information such as the infrastructure details, time taken to execute, etc. Logging
is an essential part of any software application.

.NET Core Application Types


We can create two types of applications in .NET Core.

1. Portable Application
2. Self-contained application

Portable Application
Portable applications are applications which expect .NET Core runtime on the deployment
machines. It cannot be run on a machine which does not have .NET Core runtime installed.

Self-contained Application
Self-contained applications are applications which include .NET Core runtime when we
publish it. It can run on a machine which does not have .NET Core runtime installed.

Configure Application Type ;

Configure Application TypeWe can configure ASP.NET Core application as portable


or self-contained application using type property of Microsoft. NETCore. App
dependency in project.

Code Sharing in .NET Core ;


ASP.NET core uses new SDK-style file projects which means we can easily open any file
and make changes to the file again and again. For sharing code in the controller we will
create one <ItemGroup> tag. Then after we will add the reference to the old project file to
the new project file.

Target Multiple Frameworks in .NET Core 2.x


App
As mentioned in the previous chapter, creating a .NET Core application which targets
multiple frameworks is one of the approaches for code sharing.

We can create .NET Core application and configure multiple target frameworks for it so
that it can run with all the configured target frameworks. To demonstrate this, let's create

48 | P a g e
.NET Core 2.0 console application which can run with .NET Core as well as traditional .NET
framework in Visual Studio 2017.

Here, we will support two more frameworks . NET Framework 4.0 & 4.6. So include net40
and net46 monikers respectively as shown below.

49 | P a g e
Entity Framework
Entity Framework (EF) Core is a lightweight, extensible, open source and cross-
platform version of the popular Entity Framework data access technology.

EF Core can serve as an object-relational mapper (O/RM), which: Enables .NET


developers to work with a database using .NET objects.

Microsoft introduced Entity Framework in 2008 with .NET Framework 3.5

EF Core features and concepts as EF 6.

1. DbContext and DbSet.


2. Data Model.
3. Querying using Linq-to-Entities.
4. Change Tracking.
5. SaveChanges.
6. Migrations.
The Architecture of Entity Framework consists of the following
components:
• Entity Framework Core includes:

o DbContext: Represents a session with the database and a

gateway to perform CRUD operations.


o DbSet: Represents a collection of entities of a particular type

within the context.


o Entity: Represents a class that corresponds to a table in the

database.
o LINQ to Entities: Allows querying entities using LINQ.

How Entity Framework Works?

Enables .NET developers to work with a database using .NET objects.


Entity Framework API (EF6 & EF Core) includes the ability to map domain
(entity) classes to the database schema, translate & execute LINQ queries to
SQL, track changes occurred on entities during their lifetime, and save
changes to the database.

50 | P a g e
Let's understand the above EF workflow:

1. First of all, you need to define your model. Defining the model includes defining your
domain classes, context class derived from DbContext, and configurations (if any). EF
will perform CRUD operations based on your model.
2. To insert data, add a domain object to a context and call the SaveChanges() method.
EF API will build an appropriate INSERT command and execute it to the database.
3. To read data, execute the LINQ-to-Entities query in your preferred language
(C#/VB.NET). EF API will convert this query into SQL query for the underlying relational
database and execute it. The result will be transformed into domain (entity) objects and
displayed on the UI.
4. To edit or delete data, update or remove entity objects from a context and call
the SaveChanges() method. EF API will build the appropriate UPDATE or DELETE
command and execute it to the database.

Entity Data Model


The very first task of EF API is to build an Entity Data Model (EDM). EDM is an in -
memory representation of the entire metadata: conceptual model, storage model,
and mapping between them.

What is an Entity in Entity Framework?

An entity in Entity Framework is a class that maps to a database table. This class must be
included as a DbSet<TEntity> type property in the DbContext class. EF API maps each entity
to a table and each property of an entity to a column in the database.

Context Class in Entity Framework


The context class is a most important class while working with EF 6 or EF Core. It represent
a session with the underlying database using which you can perform CRUD (Create, Read,
Update, Delete) operations.

The context class in Entity Framework is a class which derives


from System.Data.Entity.DbContext in EF 6 and EF Core both. An instance of the context
class represents Unit Of Work and Repository patterns wherein it can combine multiple
changes under a single database transaction.

The context class is used to query or save data to the database. It is also used to configure
domain classes, database related mappings, change tracking settings, caching, transaction
etc.

51 | P a g e
Development Approaches with Entity Framework
There are three different approaches you can use while developing your application using
Entity Framework:

1. Database-First
2. Code-First
3. Model-First

Database-First Approach
In the database-first development approach, you generate the context and entities for the
existing database using EDM wizard integrated in Visual Studio or executing EF commands.

EF 6 supports the database-first approach extensively. Visit EF 6 DB-First section to learn


about the database-first approach using EF 6.

EF Core includes limited support for this approach.

Code-First Approach
Use this approach when you do not have an existing database for your application. In the
code-first approach, you start writing your entities (domain classes) and context class first
and then create the database from these classes using migration commands.

Developers who follow the Domain-Driven Design (DDD) principles, prefer to begin with
coding their domain classes first and then generate the database required to persist their
data.

52 | P a g e
Model-First Approach
In the model-first approach, you create entities, relationships, and inheritance hierarchies
directly on the visual designer integrated in Visual Studio and then generate entities, the
context class, and the database script from your visual model.

EF 6 includes limited support for this approach.

EF Core does not support this approach.

Choosing the Development Approach for Your Application


Use the following flow chart to decide which is the right approach to develop your
application using Entity Framework:

53 | P a g e
As per the above figure, if you already have an existing application with domain
classes, then you can use the code-first approach because you can create a
database from your existing classes. If you have an existing database, then you can
create an EDM from an existing database in the database-first approach. If you do
not have an existing database or domain classes, and you prefer to design your DB
model on the visual designer, then go for the Model-first approach.

Persistence Scenarios in Entity Framework

There are two scenarios when persisting (saving) an entity to the database
using Entity Framework: the Connected Scenario and the Disconnected
Scenario.

Connected Scenario

In the connected scenario, the same instance of the context class (derived
from DbContext) is used in retrieving and saving entities. It keeps track of all
entities during its lifetime. This is useful in windows applications with the local
database or the database on the same network.

54 | P a g e
Pros:

• Performs fast.
• The context keeps track of all entities and automatically sets an appropriate state as
and when changes occurr to entities.

Cons:

• The context stays alive, so the connection with the database stays open.
• Utilizes more resources.

Disconnected Scenario
In the disconnected scenario, different instances of the context are used to retrieve and
save entities to the database. An instance of the context is disposed after retrieving data
and a new instance is created to save entities to the database.

The disconnected scenario is complex because an instance of the context doesn't


track entities, so you must set an appropriate state to each entity before saving
entities using SaveChanges() . In the figure above, the application retrieves an entity
graph using Context 1 and then the application performs some CUD (Create,
Update, Delete) operations using Context 2. Context 2 doesn't know what operation
has been performed on the entity graph in this scenario.

This is useful in web applications or applications with a remote database.

Pros:

• Utilizes less resources compared to the connected scenario.

55 | P a g e
• No open connection with the database.

Cons:

• Need to set an appropriate state to each entity before saving.


• Performs slower than the connected scenario.

How does Entity Framework handle relationships between entities (one-to-one,


one-to-many, many-to-many)?
o Entity Framework supports various types of relationships:
▪ One-to-One: One entity instance is related to exactly one instance of
another entity.
▪ One-to-Many: One entity instance is related to multiple instances of
another entity.
▪ Many-to-Many: Multiple instances of one entity are related to multiple
instances of another entity using a joining table.
Explain the advantages and disadvantages of using Entity Framework.
o Advantages: Rapid development, reduced amount of boilerplate code, easy
to maintain, supports various database providers, LINQ support for querying
data.
o Disadvantages: Performance overhead, potential for generating inefficient
queries, complexity in some advanced scenarios, learning curve.
What is the purpose of the DbContext class in Entity Framework?
o The DbContext class in Entity Framework represents the session with the
database and provides a set of APIs to perform CRUD (Create, Read, Update,
Delete) operations on entities. It also manages the entity objects during their
lifecycle.
Explain how Entity Framework handles transactions.
o Entity Framework Core supports transactions through
the SaveChanges method. Multiple changes within a
single SaveChanges call are made within a transaction.
Entity Framework introduced a migration tool that automatically updates the database
schema when your model changes without losing any existing data or other database
objects.
There are two kinds of Migration:

1.Automated Migration 2. Code-based Migration

56 | P a g e
ASP.NET Web API
API is an abbreviation for Application Programming Interface.

ASP.NET Web API is a framework for building HTTP services that can be
accessed from any client including in different applications on different
platforms such as web, windows, browsers and mobile devices.
ASP.NET Web API is a robust framework for developing HTTP-enabled service
APIs that expose services and data. It may be accessed by a wide range of clients,
including browsers, mobile devices, desktop computers, and tablets. Because it is
an HTTP service, it may reach many clients.
It is an ideal platform for building RESTful applications on the .NET
Framework.
A Browser API can be used to enhance a web browser's functionality. A Server API can
be used to enhance a web server's functionality.

.
ASP.NET Web API Characteristics
• ASP.NET Web API is an ideal platform for building RESTful services.
• ASP.NET Web API is built on top of ASP.NET and supports ASP.NET request/response pipeline.
• ASP.NET Web API maps HTTP verbs to method names.
• ASP.NET Web API supports different formats of response data.

Q1. What is the difference between ASP.NET and API?


ASP.NET MVC Controllers are used for building web applications with dynamic user interfaces,
while Web API Controllers are used for exposing data and services over HTTP for various clients

57 | P a g e
Q2. What is .NET Framework API?
A software development framework for building and running applications on Windows.

Q3. What is ASP.NET Web API 2 vs 1?


WebAPI-2 supports configuring routes at the controller level or the webAPI method level. While in
WebAPI-1 you could only configure routes in the global. asax.

Why is Web API required?


A web API is a service that retrieves information or data from a server. It is critical for
business growth. Here are some of the reasons why Web API is so important:
• Provides a data access interface for both web pages and client applications.
• Supports a variety of text formats, including XML and JSON.
• Works nicely on low-bandwidth devices.
• Commonly used in the creation of UI/UX, resulting in increased visitors to the website.
• Compatibility with any browser and device.

Why select Web API?


• It is used to develop simple HTTP Services that are not SOAP-based.
• It is also a simple way to create with Web API. REST Services with WCF
• It is HTTP-based and simple to define, expose, and consume RESTful.
• It is a lightweight architecture that is excellent for devices with limited bandwidth, such
as smartphones.

The advantages of Web API ;


Web API can automatically convert request and response data into various formats,
including JSON, XML, BSON, and url-encoded data.
This makes it easy to work with data in the format that is most convenient for you.
On the other hand, the REST API only supports the JSON data format and is, therefore,
less flexible.

When to choose ASP.NET Web API?


• Choose Web API if you are using .NET framework 4.0 or above.
• Choose Web API if you want to build a service that supports only HTTP protocol.
• Choose Web API to build RESTful HTTP based services.
• Choose Web API if you are familiar with ASP.NET MVC.

Create Web API project


Here, you will learn how to create a new ASP.NET Web API project using Visual Studio.

58 | P a g e
You can create a Web API project in two ways.

1. Web API with MVC Project


2. Stand-alone Web API Project

Stand-alone Web API Project


Here, we will create a new stand-alone Web API project without MVC project.

For this, open Visual Studio 2013 for Web -> go to File menu and select New
Project.. This will open New Project popup as below.

TestApi?
TestApi is an API utility library. Using this library, tester developers can design testing tools
and automated tests for .NET applications that use data structures and algorithms.

Test Web API


Test Web API locally to check request & response during development.

We can use the following third party tools for testing Web API.

• Fiddler
• Postman

Web API Controllers ;


In ASP.NET Web API, a controller is a class that handles HTTP requests.
All the public methods of the controller are called action methods.

Web API Controller Characteristics


1. It must be derived from System.Web.Http.ApiController class.
2. It can be created under any folder in the project's root folder. However, it is
recommended to create controller classes in the Controllers folder as per the
convention.
3. Action method name can be the same as HTTP verb name or it can start with
HTTP verb with any suffix (case in-sensitive) or you can apply Http verb
attributes to method.
4. Return type of an action method can be any primitive or complex type.

59 | P a g e
The difference between ApiController and Controller?

ApiController: It is used to return data that is arranged in series and then sent to the
client.

Controller: It is used to provide normal views.

Action Method Naming Conventions


• Name of the action methods in the Web API controller plays an important role. Action
method name can be the same as HTTP verbs like Get, Post, Put, Patch or Delete as
shown in the Web API Controller example above.
• However, you can append any suffix with HTTP verbs for more readability.
For example, Get method can be GetAllNames(), GetStudents() or any other
name which starts with Get.

Configure Web API ;


Web API supports code based configuration. It cannot be configured in web. config file.

We can configure Web API to customize the behaviour of Web API hosting infrastructure
and components such as routes, formatters, filters, DependencyResolver,
MessageHandlers, ParamterBindingRules, properties, services etc.

Web API Routing ;


• Routing is how Web API matches a URI to an action. Web API 2 supports
a new type of routing, called attribute routing.
• As the name implies, attribute routing uses attributes to define routes.
Attribute routing gives you more control over the URIs in your web API.

• Note:
• Web API also supports routing same as ASP.NET MVC by including action method name
in the URL.

60 | P a g e
Routing can be implemented in two ways:
• Convention-based routing:

Web API supports convention-based routing.


In this type of routing, Web API uses route templates to select which controller and action
method to execute.

Attribute-based routing:

Web API 2 generally supports a new type of routing known as attribute routing. As
the name suggests, it uses attributes to define routes.
It is the ability to add routes to the route table via attributes. It makes use of
characteristics to define and add routes to route tables.

Parameter Binding in ASP.NET Web API ;


Parameter binding is the process of converting request data into strongly typed
parameters that are expressed by route handlers. Binding sources can be explicit or
inferred based on HTTP method and parameter type. Supported binding sources: Route
values.
HTTP Method Query String Request Body
GET Primitive Type, NA
Complex Type

POST Primitive Type Complex Type

PUT Primitive Type Complex Type

PATCH Primitive Type Complex Type

DELETE Primitive Type, NA


Complex Type

Note:

61 | P a g e
Query string parameter name and action method parameter name must be the same (case-
insensitive). If names do not match, then the values of the parameters will not be set. The
order of the parameters can be different.

Note:
Post action method cannot include multiple complex type parameters because, at most, one
parameter is allowed to be read from the request body.

Note:
The [FromBody] attribute can be applied on only one primitive parameter of an action method.
It cannot be applied to multiple primitive parameters of the same action method.

[FromUri] and [FromBody]Use [FromUri] attribute to force Web API to get the value
of complex type from the query string and [FromBody] attribute to get the value of
primitive type from the request body, opposite to the default rules.

Action Method Return Type


Web API action method can contain any entity type as return type. As mentioned in the first
example of What is Web API Action Results, we can use any entity type as the return type.
But the problem here is that we get 200 (OK) status code every time on a successful
response.The Web API action method can have following return types.

1. Void
2. Primitive type or Complex type
3. HttpResponseMessage
4. IHttpActionResult

Void ;
void. If the return type is void , Web API simply returns an empty HTTP response
with status code 204 (No Content).
Type Primitive type or Complex type ;
The simplest action returns a primitive or complex data type (for example, string or a
custom object type).
Consider the following action, which returns a collection of custom Product objects: C#
Copy. [HttpGet] public List<Product> Get() => _repository. GetProducts() ;

62 | P a g e
HttpResponseMessage ;
A HttpResponseMessage allows us to work with the HTTP protocol (for example, with the
headers property) and unifies our return type. In simple words an HttpResponseMessage
is a way of returning a message/data from your action.
The use of HttpResponseMessage?

It is used to set response values such as header and status control. It simply allows us to
work with HTTP protocol. It represents HTTP response messages that encapsulate data
and status code.

IHttpActionResult ;
In Web API, IHttpActionResult's ExecuteAsync method is automatically
invoked when a client calls an action method, allowing custom logic to
generate a HttpResponseMessage asynchronously.

Web API Request/Response Data Formats ;

• Web API converts request data into CLR object and also serialize CLR object
into response data based on Accept and Content-Type headers.
• Web API includes built-in support for JSON, XML, BSON, and form-
urlencoded data. It means it automatically converts request/response data
into these formats OOB (out-of the box).
• Web API handles different formats of request and response data.

Media-Type Formatters :
By using Media-Type formatters. Media type formatters are classes
responsible for serializing request/response data so that Web API can
understand the request data format and send data in the format which client
expects.

Web API Filters ;


• Web API includes filters to add extra logic before or after action method
executes.
• Filters can be used to provide cross-cutting features such as logging,
exception handling, performance measurement, authentication and
authorization.

63 | P a g e
• Filters are actually attributes that can be applied on the Web API controller
or one or more action methods. Every filter attribute class must implement
IFilter interface included in System.Web.Http.Filters namespace..

Why are Filters in ASP.NET Core?


In ASP.NET Core MVC, Filters are used to Perform cross-cutting concerns. They are as
follows:
• Caching
• Logging
• Error Handling
• Modifying the Result
• Authentication and Authorization, etc.

CRUD operation ;
CRUD stands for "Create, Read, Update, and Delete," which are the four
basic database operations. Many HTTP services also model CRUD
operations through REST or REST-like APIs.

Web API for CRUD operation ;


CRUD stands for Create, Read, Update and Delete. It works on HTTP verbs like
HttpPost to Create, HttpGet to Read, HttpPut to Update, and HttpDelete to Delete.
Many of these resources allow create, read, update and delete operations. The
REST API maps CRUD operations to HTTP methods.
Many of these resources allow create, read, update and delete operations.

Implement Get Method ;


Retrieving Data from APIs
Parameters for GET requests are usually passed in the URL, and they can be
appended to the end of the URL in the form of a query string. For example, you can
use a GET request to obtain information about a specific user:
https://api.example.com/users?id=123..

Implement Post Method ;


The Post Method in the Web API application allows us to create a new item.
A POST request sends data to an API, either creating or updating an existing resource…

The HTTP POST request is used to create a new record in the data source in the
RESTful architecture.

64 | P a g e
The action method that will handle HTTP POST request must start with a word
Post. [HTTP POST]

Implement Put Method ;


The PUT method in Web API allows us to update an item.
The action method that will handle HTTP PUT request must start with a word Put.

Implement Delete Method ;


The HTTP DELETE request is used to delete an existing record in the data source
in the RESTful architecture.
The action method that will handle HTTP DELETE request must start with the
word "Delete".

Consume Web API ;


ASP.NET Web API is a framework for building HTTP services that can be consumed by a
broad range of clients including browsers, mobiles, iphone and tablets.
Consuming Web API

In this article, we have used the localhost for Web API and called the GET request.

• Create ASP.NET MVC Project


• Add MemberViewModel
• Add Microsoft.AspNet.webApi.Client from the NuGet library
• Code for consuming the Web API
• Run the project and call action method on URL

Who can consume WebAPI?


WebAPI can be used by any client that supports HTTP verbs like GET, PUT, DELETE, and POST.

Consume Web API in ASP.NET MVC ;


HttpClient sends a request to the Web API and receives a response.

Web API can be accessed in the server side code in .NET and also on client side
using JavaScript frameworks such as jQuery, AnguarJS, KnockoutJS etc.

Here, we will consume our Web API (created in the previous section) in the following
environments:

65 | P a g e
1. Consume Web API in ASP.NET MVC
2. Consume Web API in AngularJS

Consume Web API in ASP.NET MVC ;


We created Web API and implemented various Get methods to handle different HTTP
GET requests in the Implement Get Method section.
To consume Web API in ASP.NET MVC server side we can use HttpClient in the MVC
controller. HttpClient sends a request to the Web API and receives a response. We then
need to convert response data that came from Web API to a model and then render it
into a view.

1. Define the API endpoint: Know the URL of the Web API endpoint you want to consume.

2. Add HttpClient: In your ASP.NET MVC application, create an instance of HttpClient to make HTTP
requests to the Web API.

3. Make HTTP GET request: Use the HttpClient instance to make a GET request to the Web API
endpoint.

4. Process the response: Handle the response returned by the Web API, which could be JSON, XML,
or other formats.

Consume Web API in .NET using HttpClient ;


First, we have created an object of HttpClient and assigned the base address of
our Web API. The GetAsync() method sends an http GET request to the specified url.
The GetAsync() method is asynchronous and returns a Task.
we will use HttpClient class in console application to send data to and receive data from
Web API which is hosted on local IIS web server. You may use HttpClient in other .NET
applications also such as MVC Web Application, windows form application, window s
service application etc.

Configure Dependency Injection with Web API ;

66 | P a g e
In ASP.NET Web API, configure dependency injection by registering dependencies
with the chosen DI container and injecting them into controllers via constructor injection.

Web API Hosting ;


Web API hosting involves deploying the API to a server or cloud platform where it can
be accessed by clients over the internet.
You can host a Web API as separate process than ASP.NET. It means you can host a
Web API in console application or windows service or OWIN or any other process that is
managed by . NET framework.

IIS Hosting ;
Web API can be hosted under IIS, in the same way as a web application. You have
learned to create a Web API in the previous section. As you have seen there, a
Web API is created with ASP.NET MVC project by default.
Self Hosting;
You can host a Web API as separate process than ASP.NET. It means you can host
a Web API in console application or windows service or OWIN or any other process that
is managed by . NET framework.

You need to do following steps in order to self-host a web API.

1. Use HttpConfiguration to configure a Web API


2. Create HttpServer and start listening to incoming http requests

-----------------*-------------------------

State differences between MVC and WebAPI


The MVC framework is used to create applications with user interfaces. Views can be utilized to
provide a user interface for this purpose.
WebAPI is used to create HTTP services. Other programs can also use the WebAPI methods to
retrieve the data.

the difference between Web API and WCF?

WCF is used for SOAP-based service development, whereas Web API is utilized
for both SOAP-based and RESTful service development. WCF does not provide
support for MVC functionalities, although Web API does. WCF supports HTTP,
UDP, and custom transport protocols, whereas Web API only supports HTTP.

67 | P a g e
CRUD REST API
CRUD is a way of manipulating information, describing the function of an
application.

REST is controlling data through HTTP commands.

It is a way of creating, modifying, and deleting information for the user. CRUD
functions can exist in a REST API, but REST APIs are not limited to CRUD
functions.

REST API
Full form of REST API is Representational State Transfer Application Programming Interface

• REST stands for REpresentational State Transfer, and it is a completely new


way of developing a web program.
• REST APIs are HTTP-based and provide applications the ability to
communicate using lightweight JSON format. They run on web servers.
RESTFUL API
• RESTful services are those that are created using REST architectural concepts. It
focuses on system resources and how the state of those resources should be
transmitted via HTTP.
• RESTful API is an interface that two computer systems use to exchange
information securely over the internet.

different between REST API and RESTful API?

REST API uses web services and is based on request and response, whereas
RESTful API works completely based on REST application and infrastructure.

68 | P a g e
REST apps have strong protocols and pre-configured architecture layers as
security measures, whereas RESTful apps have multi-layered transport protocols.

Beetween SOAP and REST?


SOAP and REST are two different approaches to API design. The SOAP approach is
highly structured and uses XML data format. REST is more flexible and allows
applications to exchange data in multiple formats.

Web API supports which protocol?


The HTTP protocol is the primary protocol supported by Web API. This means that it makes use
of the well-established and widely recognized HTTP standards for communication between clients
and servers.

Web API supports which protocol?


Web API generally communicates over the Hypertext Transfer Protocol (HTTP). This implies it
employs HTTP methods to specify operations (GET, POST, PUT, DELETE, etc.), and HTTP
status codes to indicate response outcomes, and often transfers data in formats like JSON or XML
over HTTP.

Web API uses which library for JSON serialization?


Web API uses the Json.NET package for JSON serialization.

Which .NET framework supports ASP.NET Web API?

.NET Framework 4.0 generally supports the first version of ASP.NET Web API. After hat,
.NET Framework 4.5 supports the latest version of web API i.e., ASP.NET Web API 2

How to handle errors in Web API?


Error handling classes are accessible in Web API. HttpError, HttpResponseException, Exception
Filters, and Registering Exception Filters are among them.

Explain the method to handle errors using HttpError in Web API.


HttpError was used in WEB API to throw error information in the response body. Along with this,
you can use the "CreateErrorResponse" method, which is defined in the
"HttpRequestMessageExtension."

69 | P a g e
Which .NET framework supports Web API?
The following .NET frameworks enable Web API:
• .NET Framework 4.0 and later: Web API was first introduced in .NET Framework 4.0, and
it is now supported in all future versions, including 4.5, 4.6, and 4.8.
• Versions of .NET Core 1.0 and later: .NET Core, a cross-platform and open-source
version of .NET, has supported Web API since its initial release and will continue to do so
in future editions.
• .NET 5 and later: Web API is naturally supported by.NET 5 and later versions, which unite
the.NET Framework and.NET Core.

What is the biggest disadvantage of “Other Return Types” in Web API?


The inability to directly return non-200 status codes is the most significant downside of using
"Other Return Types" in Web API.

What is SOAP?
SOAP is an XML messaging format that is commonly used in online service interactions. It
supports sending messages via HTTP or JMS, but additional transport protocols are also
supported. It is also an XML-based messaging system used to exchange data between
computers.

What is the benefit of using REST in Web API?


REST is essential and advantageous in Web API for the following reasons:
• It enables minimal data transfer between the client and the server.

• It is simple to use and light.


• It gives you additional options.
• It also manages and regulates numerous types of calls and returns data in a variety of
forms.
• It is preferred for use in mobile apps since it requires minimal data transmission between
client and server.
• It communicates between machines using basic HTTP calls rather than more complicated
choices such as CORBA, COM+, SOAP, or RPC.

error handling in Web API.


Web API provides several error-handling classes:
• HttpResponseException: Returns the HTTP status code specified in the Constructor of
the exception.
• HttpError: Uses the HttpResponseMessage to return the meaningful error code to the
client.
• Exception filters: These are useful when the controller action method throws an unhandled
exception or error

70 | P a g e
How can you restrict access methods to specific HTTP verbs in Web
API?
With the help of Attributes (like HTTP verbs), It is possible to implement access restrictions in Web
API. It is possible to define HTTP verbs as an attribute to restrict access.

Example:
HttpPost]public void Method1(Class obj){//logic

Web service testing tools for REST APIs include:


• Jersey API
• CFX
• Axis
• Restlet

Explain the different HTTP methods.


There are 8 HTTP methods:
• GET: Uses a specific URI to retrieve data from the server.
• HEAD: Like GET, but just sends the status line and header section.
• PUT: Replace all existing resources with the uploaded content and update them.
• POST: Send data to the appropriate server.
• DELETE: Deletes all current resources specified by a URI.
• OPTIONS: Specifies the target resource's communication options.
• CONNECT: Constructs a tunnel to the server based on a URI.
• TRACE: Runs a message loop-back test along the path to the destination resource.
Can a Web API return an HTML View?
Web API cannot return an HTML view. If you want to return views, it is best to use MVC.

What is the status code for “Empty return type” in Web API?
The status code 204 will return empty content in the response payload body.

. NET is used to develop diverse kinds of applications such as web apps,


mobile apps, desktop apps, Microservices, cloud services, machine
learning, game development, and last but not least IoT applications. On
the other hand, ASP.NET is used for developing dynamic web services,
websites, and web applications only.

71 | P a g e
ASP.Net Core Mvc
MVC stands for Model, View and Controller.

ASP.NET MVC Architecture

• MVC stands for Model, View, and Controller. MVC separates an application into three
components - Model, View, and Controller.

1. Model represents the data


2. View is the User Interface.
3. Controller is the request handler.

ASP.NET MVC Version History


Microsoft introduced ASP.NET MVC in .NET 3.5 and subsequently added numerous
features over time. In April 2009, Microsoft made the ASP.NETMVC
framework open-source under the Microsoft Public License (MS-PL).
• ASP.NET MVC framework can be installed as NuGet package.
• The latest version of ASP.NET MVC version will be automatically added as a
NuGet package when you create a new ASP.NET MVC project.

why and when to use ;

ASP.NET Core MVC provides a patterns-based way to build dynamic websites that
enables a clean separation of concerns.

ASP.NET Core provides the following benefits:

• A unified story for building web UI and web APIs. Architected for
testability. Razor Pages makes coding page-focused scenarios easier and
more productive. Ability to develop and run on Windows, macOS, and Linux.

Create ASP.NET MVC Application


1. Open Visual Studio.
2. Click on "Create a new project."
3. Choose "ASP.NET Web Application" from the list of project templates.

72 | P a g e
4. Give your project a name and location, then click "Create."
5. In the "Create a new ASP.NET Core web application" dialog, select "ASP.NET Core Web App
(Model-View-Controller)".
6. Choose your preferred .NET Core version and authentication method (if needed), then click
"Create."
7. Visual Studio will generate the basic structure for your ASP.NET MVC application, including
controllers, views, and models.
8. You can start adding functionality to your application by creating controllers, defining routes, and
designing views.

ASP.NET MVC Folder Structure

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 holds files that run when theapp
starts.Common ones include AuthConfig.cs,BundleConfig.cs,
FilterConfig.cs,and RouteConfig.cs. MVC 5 comes with
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.

fonts
The Fonts folder contains custom font files for your application.

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.

73 | P a g e
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.

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

----------------------------------------

Features ;
ASP.NET MVC lets you use features such as forms authentication and Windows
authentication, URL authorization, membership and roles, output and data caching,
session and profile state management, health monitoring, the configuration system, and
the provider architecture.

Models
• 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.
• In the ASP.NET MVC Application, all the Model classes must be created in the
Model folder.
• 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.

View:
• View in MVC is a user interface. View display model data to the user and also
enables them to modify them.
• The Views folder contains HTML files for the application. CSS, and some special
syntax (Razor syntax) that makes it easy to communicate with the model and
the controller.
• Typically view file is a .cshtml file where you write HTML and C# or VB.NET code.

74 | P a g e
• 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.
• The Shared folder under the View folder contains all the views shared among
different controllers e.g., layout files.

Controllers
• A Controller handles users' request and returns a response.
• The user uses the view and raises an HTTP request, which will be handled
by the controller. The controller processes the request and returns the
appropriate view as a response.
• The Controllers folder contains class files for the controllers.

Points to Remember :

• The Controller handles incoming URL requests. MVC routing sends requests to
the appropriate controller and action method based on URL and configured
Routes.
• All the public methods in the Controller class are called Action methods.
• The Controller class must be derived from System.Web.Mvc.Controller class.
• The Controller class name must end with "Controller".
• A new controller can be created using different scaffolding templates. You can
create a custom scaffolding template also.

75 | P a g e
Routing in MVC
Routing is the process of directing the HTTP requests to the right controller.

Routing in MVC refers to the process of mapping incoming browser requests to specific
controller actions and views. It determines how URLs are interpreted and handled by the
application.

Points to Remember :

1. Routing plays important role in the MVC framework. Routing maps URL to physical
file or class (controller class in MVC).

2. Route contains URL pattern and handler information. URL pattern starts after the
domain name.
3. Routes can be configured in RouteConfig class. Multiple custom routes can also be
configured.
4. Route constraints apply restrictions on the value of parameters.
5. Route must be registered in Application_Start event in Global.ascx.cs file.

Attribute Routing
If we are defining Routes by using the [Route] attribute is called Attribute
Routing. It provides you more control over the URIs by defining routes directly
on actions and controllers in your ASP.NET MVC application.

76 | P a g e
Action method
action methods are responsible to execute the request and generate a response to
it
Points to Remember :

1. All the public methods in the Controller class are called Action methods.
2. The Action method has the following restrictions.
- Action method must be public. It cannot be private or protected.
- Action method cannot be overloaded.
- Action method cannot be a static method.
3. ActionResult is a base class of all the result type which returns from Action method.
4. The base Controller class contains methods that returns appropriate result type e.g.
View(), Content(), File(), JavaScript() etc.
5. The Action method can include Nullable type parameters.

6.If we want the public method to be a non-action method, then we can decorate the action method
by “NonAction” attribute.

Action Selectors
Action selector is the attribute that can be applied to the action methods. It helps
the routing engine to select the correct action method to handle a particular request.
MVC 5 includes the following action selector attributes:

1. ActionName ,[ActionName(“Found”)]
2. NonAction ,[ NonAction]
3. ActionVerbs

ActionVerbs:
HttpGet, HttpPost, HttpPut

The ActionVerbs selector is to handle different type of Http requests. The MVC
framework includes HttpGet, HttpPost, HttpPut, HttpDelete, HttpOptions, and
HttpPatch action verbs.

we can apply one or more action verbs to an action method to handle different
HTTP requests. If you don't apply any actionverbs to an action method, then it will
handle HttpGet request by default.

HttpGet: This attribute indicates that the action method should only respond to HTTP
GET requests. It's commonly used for actions that retrieve data and render views.
77 | P a g e
HttpPost: This attribute restricts the action method to only respond to HTTP POST
requests. It's typically used for actions that modify data, such as form submissions.

HttpPut: This attribute restricts the action method to only respond to HTTP PUT requests.
It's often used for actions that update existing resources.

HttpDelete: This attribute restricts the action method to only respond to HTTP DELETE
requests. It's commonly used for actions that delete resources or data from the server.

Razor View Engine ;


The Razor View Engine in MVC enables developers to seamlessly integrate server-side code
with HTML markup to generate dynamic web pages efficiently.

.cshtml C# Razor view. Supports C# code with html tags.


.vbhtml Visual Basic Razor view. Supports Visual Basic code with html tags.
.aspx ASP.Net web form
.ascx ASP.NET web control

Note:

• Every view in the ASP.NET MVC is derived from WebViewPage class included
in System.Web.Mvc namespace.

Integrate MVC ;
In MVC, the Controller receives requests, interacts with the Model for data manipulation,
and selects the View for rendering, enabling a structured and modular approach to web
application development.

Bind Query String to an Action Method Parameters in MVC ;


In MVC, you can bind query string parameters to action method parameters by naming
them the same in the method signature, allowing automatic binding during request

processing

78 | P a g e
This binding is case insensitive. So "id" parameter can be "ID" or "Id".

The Default Value Provider Collection in MVC evaluates values from the following sources:
RouteData, QueryString, Form, and Cookies.

Razor Syntax
Razor is a view engine in ASP.NET MVC that enables mixing HTML with server-side code in
either C# or Visual Basic.
View files using Visual Basic syntax have a .vbhtml extension, while those using C# syntax have
a .cshtml extension.

Razor syntax has the following Characteristics:

• Compact: Razor syntax is compact, enabling you to minimize the number of


characters and keystrokes required to write code.
• Easy to Learn: Razor syntax is easy to learn where you can use your familiar
language C# or Visual Basic.
• Intellisense: Razor syntax supports statement completion within Visual Studio.
• C# Razor Syntax;

<h1>Razor syntax demo</h1>


<h2>@DateTime.Now.ToShortDateString()</h2>
HTML Helpers ;
• HTML Helpers in MVC are methods that generate HTML markup for elements like
forms, inputs, links, and more, simplifying the creation of HTML elements within view
files.
• They help maintain clean, readable code and promote code reuse by encapsulating
common HTML patterns into reusable components.

Extension Strongly Typed


Method Method Html Control
Html.ActionLink() NA <a></a>
Html.TextBox() Html.TextBoxFor() <input type="textbox">
Html.TextArea() Html.TextAreaFor() <input type="textarea">
Html.CheckBox() Html.CheckBoxFor() <input type="checkbox">
Html.RadioButton() Html.RadioButtonFor() <input type="radio">
Html.DropDownList() Html.DropDownListFor() <select>
<option>
</select>
Html.ListBox() Html.ListBoxFor() multi-select list box: <select>
Html.Hidden() Html.HiddenFor() <input type="hidden">

79 | P a g e
Extension Strongly Typed
Method Method Html Control
Html.Password() Html.PasswordFor() <input type="password">
Html.Display() Html.DisplayFor() HTML text: ""
Html.Label() Html.LabelFor() <label>
Html.Editor() Html.EditorFor() Generates Html controls based on data type of specified
model property e.g. textbox for string property,
numeric field for int, double or other numeric type.

Exception Handling in ASP.NET MVC


• In MVC, you can use try-catch blocks in your action methods to handle specific
exceptions, but there might still be some unforeseen errors that slip through.
To address this, you can log these exceptions and display custom error
messages or pages to users.
• When you start a new MVC project in Visual Studio, it doesn't automatically set
up exception handling. So, if an unexpected error occurs, users will see a generic
error page.

ASP.NET provides the following ways to handle exceptions:

1. Using <customErrors> element in web.config


2. Using HandleErrorAttribute
3. Overriding Controller.OnException method
4. Using Application_Error event of HttpApplication

Implement Data Validation in MVC ;

Data validation is a key aspect of developing web applications. In Asp.Net MVC,


we can easily apply validation to web applications by using Data Annotation attribute
classes to model classes.

Ex..
Required Specifies that a property value is required.
EmailAddress Validates an email address.
Range Specifies the numeric range constraints for the value of a property.

ValidationMessageFor
The Html.ValidationMessageFor() is a strongly typed extension method. It
displays a validation message if an error exists for the specified field in
the ModelStateDictionary object.

80 | P a g e
It is recommended to
use ValidationMessageFor() than ValidationMessage() because it is strongly typed
and so performs fast and less error pron.

ValidationSummary
The ValidationSummary() extension method displays a summary of all validation
errors on a web page as an unordered list element. It can also be used to display
custom error messages.

The ValidationMessageFor displays an error message for an individual field, whereas


the ValidationSummary displays all the error messages.

Layout View;
The layout view is the same as the master page of the ASP.NET webform
application.

For example, an application UI may contain a header, left menu bar, right bar, and
footer section that remains the same on every page.

Only the center section changes dynamically, as shown below.

• To create a new layout view in Visual Studio, right-click on the Shared folder -
> select Add -> click on New Item...

Render Partial Views


A partial view is a reusable portion of a web page. It is .cshtml or .vbhtml file that
contains HTML code. It can be used in one or more Views or Layout Views. You can
use the same partial view at multiple places and eliminates the redundant code.

Let's create a partial view for the following menu, so that we can use the same
menu in multiple layout views without rewriting the same code everywhere.

ASP.NET MVC - ViewBag


The ViewBag in ASP.NET MVC is used to transfer temporary data (which is not
included in the model) from the controller to the view.

Internally, it is a dynamic type property of the ControllerBase class which is the


base class of the Controller class.

81 | P a g e
ViewBag Limitations ; ViewBag doesn't require typecasting while retrieving values
from it

ASP.NET MVC - ViewData


In ASP.NET MVC, ViewData is similar to ViewBag, which transfers data from Controller to
View. ViewData is of Dictionary type, whereas ViewBag is of dynamic type. However, both
store data in the same dictionary internally.

ViewData is a dictionary, so it contains key-value pairs where each key must be a string.

Points to Remember :

1. ViewData transfers data from the Controller to View, not vice-versa.


2. ViewData is a dictionary type.
3. ViewData's life only lasts during the current HTTP request. ViewData values will be
cleared if redirection occurs.
4. ViewData value must be typecast to an appropriate type before using it.
5. ViewBag internally inserts data into ViewData dictionary. So the key of ViewData and
property of ViewBag must NOT match.

ASP.NET MVC - TempData

TempData is used to transfer data from view to controller, controller to view, or from one
action method to another action method of the same or a different controller.

TempData stores the data temporarily and automatically removes it after retrieving a
value.

Filters
ASP.NET MVC Filters are used to inject extra logic at the different levels of MVC
Framework request processing. Filters provide a way for cross cutting concern (logging,
authorization, and caching).

Why are Filters in ASP.NET Core MVC?


In ASP.NET Core MVC, Filters are used to Perform cross-cutting concerns. They are as
follows:
• Caching
• Logging
• Error Handling
• Modifying the Result
• Authentication and Authorization, etc.

82 | P a g e
Action Filters
Action filters in MVC run before and after an action method executes. You can apply them to individual
actions or to entire controllers. When applied to a controller, they affect all actions within it.

Bundling and Minification


Bundling and minification techniques were introduced in MVC 4 to improve request load time.
Bundling allows us to load the bunch of static files from the server in a single HTTP request.

Minification
Minification technique optimizes script or CSS file size by removing unnecessary white space and
comments and shortening variable names to one character.

Bundle Types
MVC 5 includes following bundle classes in System.web.Optimization namespace:

ScriptBundle: ScriptBundle is responsible for JavaScript minification of single or multiple


script files.

StyleBundle: StyleBundle is responsible for CSS minification of single or multiple style


sheet files.

DynamicFolderBundle: Represents a Bundle object that ASP.NET creates from a folder


that contains files of the same type.

Area ;
Areas were introduced in Asp.net MVC2 which allow us to organize models, views, and
controllers into separate functional sections of the application, such as administration,
billing, customer support, and so on. A single MVC application may have any number of
Areas.

83 | P a g e
SQL Server

SQL Server
SQL Server is a relational database management system (RDBMS) by Microsoft.
It supports SQL along with additional features known as T-SQL or Transact-SQL.
Microsoft provides set of tools to manage local or remote SQL Server databases
such as SSMS (SQL Server Management Studio), SQL Server Agent, SQL Server
Analysis Services, SQL Server Reporting Services, SQL Server Integration
Services, etc.

Data
Data is information that can be interpreted and used by computers.
It is a collection of facts, such as numbers, words, measurements, observations
or even just descriptions of things.

Database
A database is an electronically stored, systematic collection of data.
It can contain any type of data, including words, numbers, images, videos, and
files. You can use software called a database management system (DBMS) to
store, retrieve, and edit data.

RDBMS
A relational database management system (RDBMS) is a program used to
create, update, and manage relational databases.
Some of the most well-known RDBMSs include MySQL, PostgreSQL, MariaDB,
Microsoft SQL Server, and Oracle Database.
A relational database is a type of database that stores related data points.

DBMS
DBMS stands for Database Management System,

84 | P a g e
Database Management Systems (DBMS) are software systems used to store,
retrieve, and run queries on data. A DBMS serves as an interface between an
end-user and a database, allowing users to create, read, update, and delete data
in the database.
In DBMS, the data is stored as a file, whereas in RDBMS, data is stored in the
form of tables.

DDL
Data definition language (DDL) describes the portion of SQL that creates, alters,
and deletes database objects.

It creates, alters, and deletes database objects such as tables, views, indexes,
and users. Examples of DDL statements include CREATE, ALTER, DROP and
TRUNCATE.

DML
(Data Manipulation Language) is a type of SQL command used to manipulate data
in a database.

It inserts, updates, and deletes data from a database table. Examples of DML
statements include INSERT, UPDATE, and DELETE.

DCL
The full form of DCL is Data Control Language in Structured Query Language
(SQL). DCL commands are used to control privileges in the database.

The privileges (right to access the data) are required for performing all the
database operations, like creating tables, views, or sequences.

TCL
Transaction Control Language (TCL) is a subset of SQL commands used to
manage transactions in a database.

They allow multiple database operations to be executed as a single unit of work,


which either entirely succeeds or fails.

DQL (Data Query Language):

It is a component of the SQL statement that allows getting data from the
database and imposing order upon it. It includes the SELECT statement. This

85 | P a g e
command allows getting the data out of the database to perform operations with
it.

SQL Server Management Studio (SSMS)


SQL Server Management Studio is a free multipurpose integrated tool to access,
develop, administer, and manage SQL Server databases, Azure SQL Databases, and
Azure Synapse Analytics. SSMS allows you to manage SQL Server using a graphical
interface.

SSMS can also be used to access, configure, manage & administer Analysis services,
Reporting services, & Integration services.

Advantages

Its simple and user-friendly syntax allows even non-technical users to interact with
databases and retrieve data without having to write lengthy lines of code. SQL also
provides a standardized way of communicating with databases, ensuring that data is
consistent and uniform across different systems.

SSMS Components
SQL Server Management Studio has the following components:

• Object Explorer
• Security
• Server Objects
• Query and Text Editor
• Template Explorer
• Solution Explorer
• Visual Database Tools

------------------------------------------------

There are two authentication modes in SQL Server using which you can login and
connect with the SQL Server.

• Windows Authentication
• SQL Server Authentication

Windows Authentication
• Windows authentication mode enables local Windows authentication with SQL
Server, where you can login with your local Windows credentials.

86 | P a g e
Server Authentication
Connecting through SQL Server Authentication. When using SQL Server
Authentication, logins are created in SQL Server that aren't based on Windows user
accounts. Both the user name and the password are created by using SQL Server
and stored in SQL Server.

Advantages of SQL Server Authentication:


• Allows SQL Server to support older applications and applications built on mixed
OS.
• Allows access to web-based applications where users create their own identities.
• Allows users to connect from unknown domains.

Disadvantages of SQL Server Authentication


• Users using Windows must provide an additional set of login/password to
connect to SQL Server.
• SQL Server authentication cannot use Kerberos security protocol.
• Windows offers additional password policies that are not available for SQL
Server logins.

There are two ways to create a new User or to grant user permissions:

• Using Microsoft SQL Server Management Studio


• Using T-SQL

Create New User using SSMS


Open SQL Server management studio. In the Object Explorer, expand the
Databases node.

Assign Permissions to User in SQL Server


In the previous chapter, you learned to create a new user in the database. Here, you will
learn to grant permissions to a user in SQL Server.

You can GRANT and REVOKE permissions on various database objects in SQL Server. User
permissions are at the database level.

You can grant any or a combination of the following types of permissions:

• Select: Grants user the ability to perform Select operations on the table.
• Insert: Grants user the ability to perform the insert operations on the table.
• Update: Grants user the ability to perform the update operations on the table.

87 | P a g e
• Delete: Grants user the ability to perform the delete operations on the table.
• Alter: Grants user permission to alter the table definitions.
• References: References permission is needed to create a Foreign key
constraint on a table. It is also needed to create a Function or View WITH
SCHEMABINDING clause that references that object
• Control: Grants SELECT, INSERT, UPDATE, DELETE, and REFERENCES
permission to the User on the table.

Data Types
• In SQL Server, data type specifies the type of data that can be stored in a
column of a table such as integer data, string data, date & time, binary strings,
etc.
• SQL Server provides built-in data types for all kinds of data that can be used
within SQL Server

Naming Conventions
• SQL Server defines a set of rules (dos and don'ts) for naming SQL Server
Objects called naming convention, but also gives the user to follow their own
preferred style. It is advisable to follow a single naming convention for all
database objects consistently.

Why Use Naming Conventions


• Following a naming convention for tables, columns, and all other related
database objects like views, stored procedures, indexes, triggers, etc., are
important for the success and maintenance of a project. A database can have
many tables and users working on it. By following a naming convention, you
can spend less time finding what you need and helps in efficient database
management.

Database Object Naming Rules


• SQL Server object names should adhere to naming conventions, beginning with an alphabet or
underscore, avoiding special characters, and employing meaningful English words for clarity and
consistency.
• Tables should represent real-world entities, named with descriptive nouns, avoiding prefixes like
'tbl_', and utilizing camel case or underscores for multi-word names, ensuring they are less than
126 characters.

Create Database

88 | P a g e
• In SQL Server, a database is made up of a collection of objects like tables,
functions, stored procedures, views etc. Each instance of SQL Server can have
one or more databases.
• SQL Server databases are stored in the file system as files. A login is used to
gain access to a SQL Server instance and a database user is used to access a
database. SQL Server Management Studio is widely used to work with a SQL
Server database.

Type of Database in SQL Server


There are two types of databases in SQL Server: System Database and User
Database.

System databases are created automatically when SQL Server is installed.

• master: master database stores all system level information for an instance of
SQL Server. It includes instance-wide metadata such as logon accounts,
endpoints, linked servers, and system configuration settings.
• model: model database is used as a template for all databases created on the
instance of SQL Server
• msdb: msdb database is used by SQL Server Agent for scheduling alerts and
jobs and by other features such as SQL Server Management Studio, Service
Broker and Database Mail.
• tempdb: tempdb database is used to hold temporary objects, intermediate
result sets, and internal objects that the database engine creates.

User-defined Databases are created by the database user using T-SQL or SSMS
for your application data. A maximum of 32767 databases can be created in an
SQL Server instance.

Create New Table in SQL Server


Tables are database objects that contain all the data in a database. In a table, data
is logically organized in rows and columns. Each column represents a field and each
row represents a unique record. Each column has a data type associated with it. It
represents the type of data in that column. Each table is uniquely named in a
database.

Number of tables in a database is only limited by the number of objects allowed in


the database (2,147,483,647). A user-defined table can have up to 1024 columns.

There are two ways to create a new table in SQL Server:

• Using T-SQL Script


• Using Table Designer in SQL Server Management Studio

89 | P a g e
ALTER TABLE ADD Columns in a Table
• You can add columns to an existing table by using the ALTER TABLE statement.
• ALTER TABLE statement can also be used to rename or delete columns in an
existing table
• Use the ALTER TABLE ADD statement to add one or more columns to an existing
table.
• Syntax:
ALTER TABLE [schema_name.]table_name
ADD column_name1 data_type constraint,
column_name2 data_type constraint ...
column_nameN data_type constraint;
ALTER TABLE dbo.Employee
Add Address varchar(500) NOT NULL;

Identity Column
In SQL Server, a column in a table can be set as an identity column. It is used for
generating key values for primary key columns.

Use the IDENTITY[(seed, increment)] property with the column to declare it as an identity
column in the CREATE TABLE or ALTER TABLE statements.

Syntax:
column_name data_type IDENTITY[(seed, increment)]
Parameters:
1. Seed is the first value of the identity column.
2. Increment is the incremental value added to the identity value of the previous row.

RENAME Column or Table Name


You can rename table name, column name of an existing table, index name
by using the system stored procedure sp_rename.

Syntax:
EXEC sp_rename 'old_name', 'new_name' [, 'object_type'];

Delete Columns of a Table


Use ALTER TABLE DROP COLUMN statement to delete one or more columns of a table using
T-SQL.

Syntax:
ALTER TABLE [schema_name.]table_name
DROP column column_name1, column_name2,... column_nameN;

90 | P a g e
The following deletes the Address column of the Employee table.

ALTER TABLE dbo.Employee


DROP COLUMN Address;

Database Schema
In SQL Server, a schema is a logical collection of database objects such as tables,
views, stored procedures, indexes, triggers, functions. It can be thought of as a
container, created by a database user. The database user who creates a schema is
the schema owner.

• A schema can belong to only one database whereas a database can have one
or multiple schemas.
• There are no restrictions on the number of objects in a schema.
• SQL Server provides us with a few built-in schemas such as dbo, guest, sys,
etc.
• A database schema can be owned by a database role or an application role along
with the database user. They are called schema owners.
• dbo is the default schema for a newly created database.
• Schema ownership can be transferred from one user to another user in the same
database.
• A database user can be dropped without dropping the database objects owned
by the user. But the schema cannot be deleted if it owns database objects.

SQL Server schemas provide the following benefits: Provides more flexibility
and control for managing database objects in logical groups.

Allows you to move objects among different schemas quickly. Enables you to
manage object security on the schema level.

Tables Relations
It is important to understand and design relationships among tables in a relational
database like SQL Server. In a relational database, each table is connected to
another table using the Primary-Foreign Key constraints.

Table relationships in SQL Server database are of three types:

1. One-to-One
2. One-to-Many
3. Many-to-Many

The following query will display data from all the tables.

91 | P a g e
4. SELECT * FROM Employee
5. SELECT * FROM EmployeeSkill
6. SELECT * FROM SkillDescription

Primary Key
Here you will learn what is a primary key and how to create it in a new or existing
table in the SQL Server database.

What is Primary Key?


In SQL Server, a Primary key is a constraint that uniquely identify each row in the
table. It enforce data integrity in tables.

• A table can have only one primary key.


• A primary key can be defined on one column or the combination of multiple
columns known as a composite primary key.
• A primary key cannot exceed 16 columns and a total key length of 900 bytes.
• The primary key uniquely identifies each row in a table. It is often defined on
the identity column.
• The Primary key column do not allow NULL or duplicate values. It will raise an
error if try to do so.
• All columns defined within the primary key constraint must be defined as a NOT
NULL column.
• If clustered or nonclustered is not specified, then a unique clustered index for
the primary key column will be created if there no clustered index on the table.
This makes retrieving data faster whenever the primary key column is included
in the query.

Delete a Primary Key

ALTER TABLE Employee


DROP CONSTRAINT PK_Employee_EmployeeID;

What is Foreign Key?


The foreign key establishes the relationship between the two tables and enforces
referential integrity in the SQL Server. For example, the following Employee table has
a foreign key column DepartmentID that links to a primary key column of
the Department table.

• A foreign key column can be linked to a primary key or a unique key column of
the same or another table.
• Foreign key constraints can reference tables within the same database in the
same server.

92 | P a g e
• Foreign key constraints can be defined to reference another column in the same
table. This is referred to as a self-reference.

It is used to create relationships between two tables by associating rows of


one table with that of another.
Delete a Foreign Key using T-SQLUse the ALTER TABLE DROP
CONSTRAINT command to delete a foreign key constraint in an existing
table.

Check Constraints
In SQL Server, a check constraint is used to specify the limitation on the values of a column
when inserting or updating.

The CHECK constraint is used to limit the value range that can be placed in a column.

If you define a CHECK constraint on a column it will allow only certain values for this
column.

CREATE TABLE Employee(EmployeeID int,


FirstName nvarchar(50) NOT NULL,
Salary int,
ADD CONSTRAINT CHK_Emp_Salary
CHECK(Salary > 2000 AND Salary < 4000))

Unique Key Constraints


The Unique Constraint ensures the uniqueness of all values and no duplicate values
are entered in a column of a table.

Views
In SQL Server, a view is a virtual table whose values are defined by a query. In
another word, a view is a name given to a query that can be used as a table. The
rows and columns of a view come from tables referenced by a query.

“ Views can also be used when you copy data to and from SQL Server to improve
performance and to partition data.”

it is easier to make changes to the underlying table structure.

It also highlights how we can create, query, modify, and destroy views using standard SQL
syntax.

93 | P a g e
Important Points

• Unless indexed, a view does not exist as a stored set of data values in a
database.
• Views can be created by using tables or other views in the current or other
databases.
• The SQL statements comprising the view are stored in the database and not the
resulting data.
• The data from a view is generated dynamically when a view is referenced.

Functions
• Functions in SQL Server are similar to functions in other programming
languages. Functions in SQL Server contains SQL statements that perform
some specific tasks. Functions can have input parameters and must return a
single value or multiple records.

Types of Functions
SQL Server Functions are of two types:

System Functions: These are built-in functions available in every database. Some
common types are Aggregate functions, Analytic functions, Ranking functions,
Rowset functions, Scalar functions.

User Defined Functions (UDFs): Functions created by the database user are
called User-defined functions. UDFs are of two types:

1. Scalar functions: The function that returns a single data value is called a scalar
function.
2. Table-valued functions: The function that returns multiple records as a table
data type is called a Table-valued function. It can be a result set of a single
select statement.

Advantage of User-defined Functions


• Faster Execution: Similar to stored procedures, UDFs reduce the compilation
cost of T-SQL by caching the plans and reusing them for future executions.
• Reduce Network Traffic: The SQL statements of a function execute in the
database, and the application calling it needs to make a function call to the
database.
• Supports Modular Programming: UDFs can be modified independently of the
application source code

94 | P a g e
Stored Procedures
A stored procedure is a group of SQL statements that are created and stored in a
database management system, allowing multiple users and programs to share and
reuse the procedure. A stored procedure can accept input parameters, perform the
defined operations, and return multiple output values.

the main use of stored procedure?


Security: Stored procedures allow you to enhance the security of an
application or a database by restricting the users from direct access to the
table. Low network traffic: The server only passes the procedure name instead
of the whole query, reducing network traffic.

Stored procedures are of two types:

User-defined procedures: A User-defined stored procedure is created by a


database user in a user-defined database or any System database except the
resource database.

System procedures: System procedures are included with SQL Server and are
physically stored in the internal, hidden Resource database and logically appear in
the sys schema of all the databases. The system stored procedures start with
the sp_ prefix.

Advantages of Stored procedures


• Stored procedures are reusable. Multiple users in multiple applications can
use the same Stored Procedure (SP)
• As SPs reside in the database, it reduces network traffic. Applications have
to make a procedure call to the database and it communicates back to the
user.
• Database objects are encapsulated within a stored procedure, and this
acts as a security mechanism by restricting access to the database objects.
• Reduced development cost, easily modified, and increased readability.
• Improves performance. When a stored procedure is executed for the first
time, the database processor creates an execution plan which is re-used
every time this SP is executed

Stored Procedure Parameters: Input, Output, Optional

95 | P a g e
Here you will learn about stored procedure parameters, optional parameters,
and executing stored procedures with parameters in SQL Server.

• A stored procedure can have zero or more INPUT and OUTPUT parameters.
• A stored procedure can have a maximum of 2100 parameters specified.
• Each parameter is assigned a name, a data type, and direction like Input,
Output, or Return. If a direction is not specified, then by default, it is Input.
• You can specify a default value for the parameters.
• Stored procedures can return a value to the calling program if the
parameter is specified as OUTPUT.
• The parameter values must be a constant or a variable. It cannot be a
function name.
• Parameter variables can be either user-defined or system variables like @spid

Parameter Names
• The stored procedure parameters names must start with a single @.
• The name must be unique in the scope of the stored procedure.
• If parameter values are passed as @Param1 = value1, @ Param2 = value2 as
shown in the above example, then the parameters can be passed in any order.

OUTPUT Parameters
• The OUTPUT parameter is used when you want to return some value from the
stored procedure. The calling program must also use the OUTPUT keyword
while executing the procedure.

Optional Parameters
• SQL Server allows you to specify the default values for parameters. It allows
you to skip the parameters that have default values when calling a stored
procedure.

Indexes :
Clustered Indexes
An Index in SQL Server is a data structure associated with tables and views that
helps in faster retrieval of rows.

Data in a table is stored in rows in an unordered structure called Heap. If you have
to fetch data from a table, the query optimizer has to scan the entire table to
retrieve the required row(s). If a table has a large number of rows, then SQL Server

96 | P a g e
will take a long time to retrieve the required rows. So, to speed up data retrieval,
SQL Server has a special data structure called indexes.

An index is mostly created on one or more columns which are commonly used in
the SELECT clause or WHERE clause.

There are two types of indexes in SQL Server:

1. Clustered Indexes
2. Non-Clustered Indexes

Clustered Indexes
3. The clustered index defines the order in which the table data will be sorted
and stored. As mentioned before, a table without indexes will be stored in an
unordered structure. When you define a clustered index on a column, it will
sort data based on that column values and store it. Thus, it helps in faster
retrieval of the data.
4. There can be only one clustered index on a table because the data rows can
be stored in only one order.
5. When you create a Primary Key constraint on a table, a unique clustered index
is automatically created on the table.

Non-Clustered Indexes
SQL Server provides two types of indexes, clustered and non-clustered
indexes. Here you will learn non-clustered indexes.
The non-clustered index does not sort the data rows physically. It creates a
separate key-value structure from the table data where the key contains the
column values (on which a non-clustered index is declared) and each value
contains a pointer to the data row that contains the actual value.

Modify Index
To add, remove, or change the position of an index column, you must drop and
recreate the index. However, you can set several options on the index using ALTER
INDEX statement.

Triggers in SQL Server


The trigger is a database object similar to a stored procedure that is executed
automatically when an event occurs in a database. There are different kinds of
events that can activate a trigger like inserting or deleting rows in a table, a user

97 | P a g e
logging into a database server instance, an update to a table column, a table is
created, altered, or dropped, etc.

There are three types of triggers in SQL Server

• DML triggers are automatically fired when an INSERT, UPDATE or DELETE event
occurs on a table.
• DDL triggers are automatically invoked when a CREATE, ALTER, or DROP event
occurs in a database. It is fired in response to a server scoped or database
scoped event.
• Logon trigger is invoked when a LOGON event is raised when a user session is
established.

Sequence in SQL Server


In SQL Server, the sequence is a schema-bound object that generates a sequence
of numbers either in ascending or descending order in a defined interval. It can be
configured to restart when the numbers get exhausted.

• A Sequence is not associated with any table.


• You can refer a sequence to generate values with specific increment and interval
on each execution by using NEXT VALUE FOR. You don't need to insert a row in a
table (like identity column) to generate the sequence.

Synonyms in SQL Server


• In SQL Server, the synonym is the database object that provides alternate
name (alias) to another database objects such as table, view, stored
procedure, etc. in the local server or a remote server. It provides a layer of
abstraction and protects the client application in case of a name change or
location change made to the base object.

Create Synonym
A few points to consider while creating a synonym:

• A synonym must have a unique name just like other database objects in a
schema.
• A synonym cannot be a base object for another synonym.
• A synonym cannot reference a user -defined aggregate function.

IF ELSE Statement in SQL Server

98 | P a g e
The IF ELSE statement controls the flow of execution in SQL Server. It can be
used in stored-procedures, functions, triggers, etc. to execute the SQL
statements based on the specified conditions.

Loops in SQL Server


In SQL Server, a loop is the technique where a set of SQL statements are executed
repeatedly until a condition is met.

SQL Server supports the WHILE loop. The execution of the statements can be
controlled from within the WHLE block using BREAK and CONTINUE keywords.

----------------------------------- * -------------------------------------------

Insert Data into Tables in SQL Server using INSERT Statement


The INSERT INTO statement is used to insert single or multiple records into a table
in the SQL Server database.

Syntax:
INSERT INTO table_name(column_name1, column_name2...)

VALUES(column1_value, column2_value...);

Update data in a Table using UPDATE Statement


SQL Server supports the standard SQL to update the data in the table. Use the
UPDATE TABLE statement to update records in the table in SQL Server.

Syntax:
UPDATE table_name

SET column_name1 = new_value,

column_name2 = new_value,

...

[WHERE Condition];

99 | P a g e
Note that the WHERE clause is optional, but you should use it to update the
specific record.
Delete Data using DELETE Statement
Use the DELETE statement to delete data from the existing table in the current
schema or tables of the schema on which you have the DELETE privilege.

Syntax:
DELETE FROM table_name [WHERE Condition];

SQL Server - SELECT Statement


In SQL Server, the SELECT statement is used to retrieve rows/columns data from
one or more existing tables. It follows the SQL (Structured Query Language)
standards.

SELECT column1, column2,...columnN

FROM table_name

Advantage of Alias:

• Alias makes a column more readable in the result set.


• Alias is used to give a small, abbreviated, and meaningful name to tables in the
query so that it will be easy to refer tables in joining multiple tables.
• Alias helps us to identify which column belongs to which table in case of getting
data from multiple tables.

WHERE Clause
In SQL Server, the SELECT statement can have an optional WHERE clause to filter
the data. The WHERE clause can include one or more boolean conditions to filter
out data of the tables.

The WHERE clause always comes after the FROM clause and before GROUP BY,
HAVING, and ORDER BY clauses.

100 | P a g e
GROUP BY Clause
In SQL Server, the GROUP BY clause is used to get the summary data based on one
or more groups. The groups can be formed on one or more columns. For example,
the GROUP BY query will be used to count the number of employees in each
department, or to get the department wise total salaries.

You must use the aggregate functions such as COUNT(), MAX(), MIN(), SUM(), AVG(), etc.,
in the SELECT query. The result of the GROUP BY clause returns a single row for
each value of the GROUP BY column.

Syntax:
SELECT column1, column2,...columnN FROM table_name

[WHERE]

[GROUP BY column1, column2...columnN]

[HAVING]

[ORDER BY]

HAVING Clause
In SQL Server, the HAVING clause includes one or more conditions that should be
TRUE for groups of records. It is like the WHERE clause of the GROUP BY clause.
The only difference is that the WHERE clause cannot be used with aggregate
functions, whereas the HAVING clause can use aggregate functions.

The HAVING clause always comes after the GROUP BY clause and before the ORDER
BY clause.

Syntax:
SELECT column1, column2,...columnN

FROM table_name

[WHERE]

[GROUP BY column1, column2...columnN]

101 | P a g e
[HAVING conditions]

[ORDER BY]

ORDER BY Clause
In SQL Server, the ORDER BY clause is used in the SELECT query to sort the result
in ascending or descending order of one or more columns.

Syntax:
SELECT column1, column2,...columnN

FROM table_name

[WHERE]

[GROUP BY]

[HAVING]

[ORDER BY column(s) [ASC|DESC]]

ORDER BY Characteristics:

• The ORDER BY clause is used to get the sorted records on one or more columns
in ascending or descending order.
• The ORDER BY clause must come after the WHERE, GROUP BY, and HAVING
clause if present in the query.
• Use ASC or DESC to specify the sorting order after the column name. Use ASC
to sort the records in ascending order or use DESC for descending order. By
default, the ORDER BY clause sort the records in ascending order if the order is
not specified.

INNER JOIN Query


The INNER JOIN query is used to retrieve the matching records from two or more
tables based on the specified condition. SQL Server follows the SQL stadards for
inner join queries.

102 | P a g e
Syntax:
SELECT table1.column_name(s), table2.column_name(s)

FROM table1

INNER JOIN table2

ON table1.column_name = table2.column_name;

LEFT JOIN Query


The LEFT JOIN is a type of inner join where it returns all the records from the left
table and matching records from the right table. Here, the left table is a table that
comes to the left side or before the "LEFT JOIN" phrase in the query, and the right
table refers to a table that comes at the right side or after the "LEFT JOIN" phrase.
It returns NULL for all non-matching records from the right table.

In some databases, it is called LEFT OUTER JOIN.

RIGHT JOIN Query


The RIGHT JOIN is the reverse of LEFT JOIN. The RIGHT JOIN query returns all the
records from the right table and matching records from the left table.

Here, the right side table is a table that comes to the right side or after the "RIGHT
JOIN" phrase in the query, and the left table is a table that comes at the left side
or before the "RIGHT JOIN" phrase.

The RIGHT JOIN returns NULL for all non-matching records from the left table. In
some databases, it is called RIGHT OUTER JOIN.

FULL JOIN Query


The FULL JOIN returns all the records all the specified tables. It includes NULL for
any non-matching records.

In some databases, FULL JOIN is called FULL OUTER JOIN. It can return a very large
result set because it returns all the rows from all the tables.

103 | P a g e
Self-Join in SQL Server
In SQL Server, the self-join is like a regular join, but it joins a table to itself. Similar
to any other join, a self-join requires at least two tables. But instead of adding a
different table to the join, you add another instance of the same table. It is a join
between two copies of the same table. Self-join is mainly used for querying the
hierarchical data stored in a single table.

There is no Self Join keyword. You write a normal join where both the tables
involved in the join are the same.

The following is the syntax of the self-join query.

Syntax: Self-join

Copy
SELECT a.column1, b.column2
FROM table1 a, table1 b
WHERE condition;

Dynamic SQL in SQL Server


Dynamic SQL is a programming technique where you build SQL query as a string
and execute it dynamically at runtime. It lets you build the general-purpose query
on the fly using variables, based on the requirements of the application. This makes
a dynamic SQL more flexible as it is not hardcoded.

For example, the following is a dynamic SQL.

Example: Dynamic SQL

Copy
DECLARE @sql nvarchar(max) --declare variable
DECLARE @empId nvarchar(max) --declare variable for parameter

set @empId = '5' --assign value to parameter variable


set @sql = 'SELECT * FROM EMPLOYEE WHERE EMPID =' + @empId --build query
string with parameter

exec(@sql) --execute sql query

104 | P a g e
Built-in Functions
The following is the list of built-in String functions, DateTime functions, Numeric
functions and conversion functions.

CHAR Returns a character for an ASCII value.

CONCAT Concatenates two or more string values in an end to end manner and returns
a single string.
UPPER Converts a lowercase string to uppercase.
LOWER Converts a string to lower case.
CURRENT_TIMESTAMP Returns the current system date and time of the computer on which the SQL
server instance is installed. Time zone is not included.
DATEADD Returns a new datetime value by adding an interval to the specified datepart
of the specified date
AVG Returns the average value of an expression/column values.
COUNT Returns the number of records in the SELECT query.
MAX Returns the maximum value in an expression.
MIN Returns the minimum value in an expression.
RAND Returns a random floating point value using an optional seed value.
ROUND Returns a numeric expression rounded to a specified number of places right
of the decimal point.
CONVERT Converts and formats a value of one data type to another data type.
USER_NAME Returns the current logged-in user name.

105 | P a g e
Debugging
Debugging is the process of detecting and correcting errors in a program.
There are different kinds of errors, which you are going to deal with. Some of
them are easy to catch, like syntax errors, because they are taken care of by
the compiler.

Testing
Unit testing, in C# or otherwise, is the process of testing an application with
automatic tests written in a programming language.
This testing is done by combining code units and verifying that the output is
correct.
Software testing is the process of evaluating and verifying that a software
product or application does what it's supposed to do. The benefits of good
testing include preventing bugs and improving performance.

Troubleshooting
Troubleshooting is a systematic approach to solving a problem.
Computer troubleshooting is the process of diagnosing and solving
computer errors or technical problems.
Debugging involves identifying and fixing errors in code, while
troubleshooting involves identifying and solving problems with the code or
system.

The Functionalities
The function is a block of code that has a signature.
Functional Programming in C# teaches readers to apply functional
thinking to real-world scenarios.

106 | P a g e
C# contains multiple aspects. LINQ, delegates, method extensions, Tuples,
local functions, immutability, and method chaining are the best examples of
the functional features of C# language.

Authentication
authentication is the process of determining a user's identity.

In simple words Authentication is the process of verifying a user or device


before allowing access to a system or resources.

authentication scheme that is built into the HTTP protocol.

In ASP.NET Core, authentication is handled by the authentication service,


IAuthenticationService, which is used by authentication middleware.

Authorization
Authorization is the process of determining whether a user has access to a resource.

Authorization refers to the process that determines what a user is able to do.

For example, an administrative user is allowed to create a document library, add


documents, edit documents, and delete them

Caching
Caching makes a copy of data that can be returned much faster than from the
source.

Caching is one of the simplest techniques to significantly improve your application's


performance.

It's the process of temporarily storing data in a faster access location.

Apps should be written and tested to never depend on cached data. ASP.NET Core
supports several different caches. The simplest cache is based on the
IMemoryCache. IMemoryCache represents a cache stored in the memory of the web
server.

Mapping
107 | P a g e
mapping is a critical technique in software development that involves converting data
from one object type into another.

AutoMapper in C# is a library used to map data from one object to another in


web development.

The Mapping will have the information on how the Conceptual Models are
mapped to Storage Models.

A desktop application
A desktop application is a dedicated software program designed to run on a
standalone computer, enabling end-users to execute specific tasks.

Examples include Microsoft Office, VLC Media Player, and Windows File
Explorer.

web application
Any service offered over the Internet, by definition, is a form of Web
application. Examples of Web applications therefore include online forms,
shopping carts, video streaming, social media, games, and e-mail.
Websites
Websites that use web services to access and display map data from a major
service like Google Maps are an example of these client applications.
A Web Application is meant for humans to read, while a Web Service is
meant for computers to read.

Application software
Application software is a type of computer program that performs a specific
personal, educational, and business function.
Ex;
Web browsers like Firefox, and Google Chrome, as well as Microsoft Word and
Excel.

108 | P a g e
The cloud
The cloud is an extensive network of remote servers around the world.
These servers store and manage data, run applications, and deliver content
and services like streaming videos, web mail, and office productivity software
over the internet.

A desktop
A desktop is a computer display area that represents the kinds of objects
found on top of a physical desk, including documents, phone books,
telephones, reference sources, writing and drawing tools, and project folders.

109 | P a g e

You might also like