Tutorials
Tutorials
C#
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.
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.
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
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.
1|Page
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
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
2|Page
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.
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.
Assignment Operators
Assignment operators are used to assign values to variables.
Comparison Operators
Comparison operators are used to compare two values (or variables).
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}";
4|Page
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.
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.
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.
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
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.
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.
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.
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.
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
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.
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
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.
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 ;
Switch Statements
Use the switch statement to select one of many code blocks to be executed.
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)
Statement 1 is executed (one time) before the execution of 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":
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.
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.
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.
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…
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.
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.
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.
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 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).
To create an enum, use the enum keyword (instead of class or interface), and
separate the enum items with a comma:
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.
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.
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 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
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.
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
19 | P a g e
Static constructors have the following properties:
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:
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
20 | P a g e
Define Generic Class
class DataStore<T>
{
public T Data { get; set; }
}
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.
• 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.
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.
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.
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.
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.
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.”
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.
}
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.
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.
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.
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.
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.
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
Most programming languages provide the following basic building blocks to build object -
oriented applications:
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.
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.
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
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).
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):
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)
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).
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.
31 | P a g e
Encapsulation
”Hides the Complexity “
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..
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.
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 ”
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
In the example below, the Car class (child) inherits the fields and methods from
the Vehicle class (parent):
- 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.
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.):
- It is useful for code reusability: reuse fields and methods of an existing class when you
create a new class.
1. Compile-time Polymorphism
2. Run-time Polymorphism
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.
Inheritance lets derived classes inherit base class members, enabling method overriding
for redefining behavior, known as runtime polymorphism.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
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.
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:
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
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 ;
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.
45 | P a g e
Configure the Default File to be Served on the Root Request
1. Default.html
2. Default.htm
3. Index.html
4. Index.htm
Environment Variable ;
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
1. UseDeveloperExceptionPage ;
46 | P a g e
2. UseExceptionHandler ;
Static files are typically located in the web root (wwwroot) folder.
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
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.
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.
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.
database.
o LINQ to Entities: Allows querying entities using LINQ.
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.
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.
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.
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.
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.
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.
Pros:
55 | P a g e
• No open connection with the database.
Cons:
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.
57 | P a g e
Q2. What is .NET Framework API?
A software development framework for building and running applications on Windows.
58 | P a g e
You can create a Web API project in two ways.
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.
We can use the following third party tools for testing Web API.
• Fiddler
• Postman
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.
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.
• 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:
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.
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.
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 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.
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..
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.
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]
In this article, we have used the localhost for Web API and called the GET request.
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
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.
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.
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.
-----------------*-------------------------
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.
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 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.
.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
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 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.
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
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.
71 | 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.
ASP.NET Core MVC provides a patterns-based way to build dynamic websites that
enables a clean separation of concerns.
• 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.
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.
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.
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.
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.
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.
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.
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.
• To create a new layout view in Visual Studio, right-click on the Shared folder -
> select Add -> click on New Item...
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.
81 | P a g e
ViewBag Limitations ; ViewBag doesn't require typecasting while retrieving values
from it
ViewData is a dictionary, so it contains key-value pairs where each key must be a string.
Points to Remember :
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).
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.
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:
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.
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.
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.
There are two ways to create a new User or to grant user permissions:
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.
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.
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.
• 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.
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.
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;
90 | P a g e
The following deletes the Address column of the Employee table.
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.
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.
• 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.
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.
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.
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.
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.
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.
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.
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.
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.
• 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.
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.
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.
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];
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];
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.
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]
[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]
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 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.
102 | P a g e
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.
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.
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
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.
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.
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
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.
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