Devop
Devop
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.
0|Page
Comments
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.
C# Variables
Variables are containers for storing data values.
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
1|Page
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.
Constants
which means unchangeable and read-only:
you can add the const keyword in front of the variable type. PI (3.14159...).
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
2|Page
Display Variables
The WriteLine() method is often used to display variable values to the console window.
int x = 5, y = 6, z = 50;
Console.WriteLine(x + y + z);
C# Identifiers
All C# variables must be identified with unique names.
Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
C# Data Types
As explained in the variables chapter, a variable in C# must be a specified data type:
C# Type Casting
Type casting is when you assign a value of one data type to another type.
3|Page
• Implicit Casting (automatically) - converting a smaller type to a larger type size
char -> int -> long -> float -> double
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:");
int age = Console.ReadLine();
Operators
Operators are used to perform operations on variables and values.
Assignment Operators
Assignment operators are used to assign values to variables.
Comparison Operators
Comparison operators are used to compare two values (or variables).
4|Page
Logical Operators
As with comparison operators, you can also test for True or False values with logical
operators.
Math
The C# Math class has many methods that allows you to perform mathematical tasks on
numbers
C# Strings
Strings are used for storing text.
You can also use the string.Concat() method to concatenate two strings:
String Interpolation ; string name = $"My full name is: {firstName} {lastName}";
Access Strings ;\
string myString = "Hello";
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.
5|Page
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.
6|Page
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.
7|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.
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;
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.
8|Page
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.
Declared using the static keyword. Declared using the readonly keyword. Declred using the const keywor
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 modified Constant varia
using ClassName.StaticMemberName . at run-time. It can only be initialized or cannot be modified a
changed in the constructor. declaration.
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.
Reference Type
9|Page
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.
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
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
10 | P a g e
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.
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.
11 | P a g e
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.
While Loop
12 | P a g e
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)
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
Nested Loops
13 | P a g e
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":
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.
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.
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
14 | P a g e
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.
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).
15 | P a g e
Methods
A method is a block of code which only runs when it is called.
Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times…
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.
16 | P a g e
{
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
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.
Objects
Objects are instances of the class that holds different data in
properties/fields and can interact with other objects.
17 | P a g e
Class Members
Fields and methods inside classes are often referred to as "Class Members":
Access Modifiers
Modifier Description
protected The code is accessible within the same class, or in a class that is inherited
internal The code is only accessible within its own assembly, but not from another
assembly
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.
18 | P a g e
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 :
Enums
An enum is a special "class" that represents a group
of constants (unchangeable/read-only variables).
Exceptions
When executing C# code, different errors can occur: coding errors made by the
programmer, errors due to wrong input, or other unforeseeable things.
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).
19 | P a g e
Exception Handling
exception handling in C# using try, catch, and finally blocks.
Finally
The finally statement lets you execute code, after try...catch,
regardless of the result:
Custom exceptions
20 | P a g e
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
NullReferenceException
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.
21 | P a g e
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.
USE :
the help of partial classes, we can split our classes into multiple files
22 | P a g e
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 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.
Indexers ;
Indexers allow instances of a class or struct to be indexed just like arrays.
An indexer can be defined the same way as property with this keyword and
square brackets [].
Note:
23 | P a g e
Indexer does not allow ref and out paramters.
Generics
generic means not specific to a particular data 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
Advantages of Generics
1. Generics increase the reusability of the code. You don't need to write code
to handle different data types.
24 | P a g e
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.
• 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.
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.
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.
25 | P a g e
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.
1. Declare a delegate
2. Create an instance and reference a method
3. Invoke a delegate
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.
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.
26 | 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
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
27 | 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.
}
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 :
28 | P a g e
4. Extension methods can be used anywhere in the application by including
the namespace of the extension method.
Stream
C# includes following standard IO (Input/Output) classes to read/write from
different sources like files, memory, network, isolated storage, etc.
29 | P a g e
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.
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.
Advantages of Initializers
• Initializer syntax makes a code more readable, easy to add elements into
the collection.
• Useful in multi-threading.
30 | P a g e
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.
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.
31 | P a g e
Difference between Hashtable and Dictionary
Hashtables and Dictionaries are two commonly used
Hashtable Dictionary
Hashtable is included in Dictionary is included in
the System.Collections namespa the System.Collections.Generic namesp
ce. ace.
Hashtable is a loosely typed Dictionary is a generic collection. So it
(non-generic) collection, this can store key-value pairs of specific data
means it stores key-value pairs types.
of any data types.
Hashtable is thread safe. Only public static members are thread
safe in Dictionary.
collection type for storing and retrieving key-value pairs.
32 | P a g e
33 | P a g e
Object Oriented Programming
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.
34 | P a g e
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.
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.
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism
Abstraction
Abstract Classes and Methods
35 | P a g e
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
---------------------------------------------------------------------
--
Interfaces ;
Another way to achieve abstraction in C#, is with interfaces.
36 | P a g e
• 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)
1) To achieve security - hide certain details and only show the important
details of an object (interface).
Encapsulation
37 | P a g e
”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.
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
Class Relations:
38 | P a g e
In object-oriented programming, classes interact with each other to
accomplish one or more features of an application..
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.
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.
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
39 | P a g e
Inheritance :
“ Parent and child class relationship ”
• Derived Class (child) - the class that inherits from another class
• Base Class (parent) - the class being inherited from
In the example below, the Car class (child) inherits the fields and
methods from the Vehicle class (parent):
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.
40 | P a g e
• 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.
Polymorphism
Polymorphism is a Greek word that means multiple forms or shapes.
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.):
1. Compile-time Polymorphism
2. Run-time Polymorphism
41 | P a g e
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.
Virtual?
Method Hiding
42 | P a g e
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.
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.
43 | P a g e
Interface Segregation Principle
Clients should not be forced to depend on methods they do not use.
Design Patterns
Design pattern in software engineering is a general, reusable solution to a
commonly occurring problem in software design.
44 | 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.
45 | P a g e
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.
Readonly
• Readonly is known as “readonly” keyword in C#.
• 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
46 | P a g e
47 | 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.
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.
.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.
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.
49 | P a g e
• 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.
50 | P a g e
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.
51 | P a g e
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.
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
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.
53 | P a g e
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 ;
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.
54 | 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.
1. UseDeveloperExceptionPage ;
2. UseExceptionHandler ;
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.
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.
57 | P a g e
Configure Application Type ;
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 .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.
58 | P a g e
59 | 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.
the database.
o LINQ to Entities: Allows querying entities using LINQ.
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.
61 | P a g e
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.
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.
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.
62 | P a g e
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.
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.
63 | 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.
Connected Scenario
64 | P a g e
applications with the local database or the database on the same
network.
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.
65 | P a g e
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.
Pros:
Cons:
• Automated Migration
• Code-based Migration
67 | P a g e
68 | P a g e
69 | 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.
70 | P a g e
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
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.
71 | P a g e
On the other hand, the REST API only supports the JSON data format and
is, therefore, less flexible.
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.
72 | P a g e
We can use the following third party tools for testing Web API.
• Fiddler
• Postman
ApiController: It is used to return data that is arranged in series and then sent to
the client.
• Note:
• Web API also supports routing same as ASP.NET MVC by including action method
name in the URL.
74 | P a g e
In this type of routing, Web API uses route templates to select which
controller and action method to execute.
Attribute-based routing:
Note:
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.
75 | P a g e
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.
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() ;
HttpResponseMessage ;
76 | P a g e
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?
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.
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.
77 | P a g e
• Filters can be used to provide cross-cutting features such as logging,
exception handling, performance measurement, authentication and
authorization.
• 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..
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.
78 | P a g e
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.
The action method that will handle HTTP POST request must start with a
word Post. [HTTP POST]
In this article, we have used the localhost for Web API and called the GET request.
79 | P a g e
Who can consume WebAPI?
WebAPI can be used by any client that supports HTTP verbs like GET, PUT, DELETE, and
POST.
•
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:
1. Define the API endpoint: Know the URL of the Web API endpoint you want to consume.
80 | P a g e
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.
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.
81 | P a g e
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.
-----------------*-------------------------
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
82 | P a g e
Full form of REST API is Representational State Transfer Application Programming Interface
REST API uses web services and is based on request and response,
whereas RESTful API works completely based on REST application and
infrastructure. REST apps have strong protocols and pre-configured
architecture layers as security measures, whereas RESTful apps have multi-
layered transport protocols.
83 | P a g e
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.
.NET Framework 4.0 generally supports the first version of ASP.NET Web
API. After that, .NET Framework 4.5 supports the latest version of web
API i.e., ASP.NET Web API 2
84 | P a g e
• .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 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.
85 | 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
54. 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.
86 | P a g e
87 | P a g e
88 | P a g e
ASP.Net Core Mvc
MVC stands for Model, View and Controller.
• MVC stands for Model, View, and Controller. MVC separates an application into
three components - Model, View, and Controller.
89 | P a g e
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.
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.
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.
90 | P a g e
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.
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.
91 | P a g e
• 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.
• 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.
92 | P a g e
Routing in MVC
Routing is the process of directing the HTTP requests to the right controller.
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.
93 | P a g e
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.
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
94 | P a g e
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.
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.
Note:
•
• Every view in the ASP.NET MVC is derived from WebViewPage class included
in System.Web.Mvc namespace.
95 | P a g e
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.
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.
96 | P a g e
• C# Razor Syntax;
• 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.
97 | P a g e
ASP.NET provides the following ways to handle exceptions:
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.
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.
Layout View;
98 | P a g e
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.
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.
99 | P a g e
Points to Remember :
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).
100 | 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.
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:
101 | P a g e
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.
102 | P a g e
103 | 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.
104 | P a g e
DBMS
DBMS stands for Database Management System,
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.
DML
(Data Manipulation Language) is a type of SQL command used to
manipulate data in a database.
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.
105 | P a g e
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 command allows getting the data out of the database to perform
operations with it.
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
106 | P a g e
Windows Authentication
• Windows authentication mode enables local Windows authentication with
SQL Server, where you can login with your local Windows credentials.
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.
There are two ways to create a new User or to grant user permissions:
107 | P a g e
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.
• 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.
• 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
108 | P a g e
convention, you can spend less time finding what you need and helps in
efficient database management.
Create Database
• 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.
109 | P a g e
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.
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.
Syntax:
110 | P a g e
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.
Syntax:
EXEC sp_rename 'old_name', 'new_name' [, 'object_type'];
Syntax:
ALTER TABLE [schema_name.]table_name
DROP column column_name1, column_name2,... column_nameN;
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.
111 | P a g e
• 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.
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.
1. One-to-One
2. One-to-Many
3. Many-to-Many
The following query will display data from all the tables.
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.
113 | P a g e
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))
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 also highlights how we can create, query, modify, and destroy views using
standard SQL syntax.
Important Points
114 | P a g e
• 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:
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.
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.
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.
116 | P a g e
• 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
Parameter Names
• The stored procedure parameters names must start with a single @.
• The name must be unique in the scope of the stored procedure.
117 | P a g e
• 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.
An index is mostly created on one or more columns which are commonly used
in the SELECT clause or WHERE clause.
1. Clustered Indexes
2. Non-Clustered Indexes
Clustered Indexes
118 | P a g e
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.
119 | P a g e
• Logon trigger is invoked when a LOGON event is raised when a user
session is established.
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.
120 | P a g e
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.
----------------------------------- * -------------------------------------------
Syntax:
INSERT INTO table_name(column_name1, column_name2...)
VALUES(column1_value, column2_value...);
Syntax:
UPDATE table_name
column_name2 = new_value,
...
[WHERE Condition];
121 | P a g e
Note that the WHERE clause is optional, but you should use it to update the
specific record.
Syntax:
DELETE FROM table_name [WHERE Condition];
FROM table_name
Advantage of Alias:
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.
122 | 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]
[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]
123 | P a g e
[GROUP BY column1, column2...columnN]
[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 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.
124 | P a g e
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.
Syntax:
SELECT table1.column_name(s), table2.column_name(s)
FROM table1
ON table1.column_name = table2.column_name;
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.
125 | P a g e
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.
There is no Self Join keyword. You write a normal join where both the tables
involved in the join are the same.
Syntax: Self-join
Copy
SELECT a.column1, b.column2
FROM table1 a, table1 b
WHERE condition;
Copy
DECLARE @sql nvarchar(max) --declare variable
DECLARE @empId nvarchar(max) --declare variable for parameter
126 | P a g e
set @empId = '5' --assign value to parameter variable
set @sql = 'SELECT * FROM EMPLOYEE WHERE EMPID =' + @empId --build
query string with parameter
Built-in Functions
The following is the list of built-in String functions, DateTime functions,
Numeric functions and conversion functions.
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.
127 | 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.
128 | P a g e
Functional Programming in C# teaches readers to apply functional
thinking to real-world scenarios.
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.
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.
Caching
Caching makes a copy of data that can be returned much faster than from the
source.
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
129 | P a g e
IMemoryCache. IMemoryCache represents a cache stored in the memory of
the web server.
Mapping
mapping is a critical technique in software development that involves
converting data from one object type into another.
The Mapping will have the information on how the Conceptual Models are
mapped to Storage Models.
130 | P a g e