Net Stack Basics
Net Stack Basics
Net Basics
.NET
C# Basics
C# .Net Basics
1.Introduction
C# .NET is an object oriented and type safe programming language which is mainly
developed to overcome the disadvantages of C and C++. C# enables developers to build
many types of secure and robust applications that run in .NET. C# has its roots in the C
family of languages and will be immediately familiar to C, C++, Java, and JavaScript
programmers.
C# programs run on .NET, a virtual execution system called the common language runtime
(CLR) and a set of class libraries. When the C# program is executed, the assembly is loaded
into the CLR. The CLR performs Just-In-Time (JIT) compilation to convert the IL code to
native machine instructions.
C# is Simple, Secure, Object Oriented, Type-Safe, platform independent, automatic garbage
collection, exception handling, multithreaded for developing different kinds of applications
such as Web, Windows Form, Console, Web Services, Mobile Apps etc which can be run on
different Operating Systems such as Windows, Linux, and Mac.
Prerequisites
Basic knowledge of C programming
Understanding of Object-Oriented Programming concepts
To Start with C#, install Visual Studio
2.C# Basics
This section includes the basic concepts and building blocks of C#.
Int
Long
Float
Double
Bool
Char
String
Value Types
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.
C# .Net Basics
When you pass a value-type variable from one method to another, the system creates a
separate copy of a variable in another method. If value got changed in the one method, it
wouldn't affect the variable in another method.
The following data types are all of value type:
Int
Struct
Bool
enum
Reference Types
A reference type contains a pointer to another memory location that holds the data. Unlike
value types, a reference type doesn't store its value directly. Instead, it stores the address
where the value is being stored. Reference type stores the address of the location where
the actual value is stored instead of the value itself.
When you pass a reference type variable from one method to another, it doesn't create a
new copy; instead, it passes the variable's address. So, if we change the value of a variable
in a method, it will also be reflected in the calling method.
String
Class
Array
Nullable Types
The default value of a reference type variable is null when they are not
initialized. Null means not referring to any object.
A value type variable cannot be null because it holds value, not a memory address. C# 2.0
introduced nullable types, using which you can assign null to a value type variable or declare
a value type variable without assigning a value to it
Declare nullable types using Nullable<t> where T is a type.
Example:
Nullable<int> i =
null;
The HasValue returns true if the object has been assigned a value; if it has not been assigned
any value or has been assigned a null value, it will return false.
C# .Net Basics
Anonymous Types
Anonymous types allow us to create new types without defining them. Anonymous type is
class type which is directly derived from “System.Object” and it cannot be cast by any type
other than the object.
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.
An anonymous type's property can include another anonymous type. An anonymous type
will always be local to the method where it is defined. It cannot be returned from the
method.
2.2 Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value. An array stores a fixed-size sequential collection of elements of the
same type. An array is used to store a collection of data.
All arrays consist of contiguous memory locations. The lowest address corresponds to the
first element and the highest address to the last element.
Multi-Dimensional Array
Arrays can have more than one dimension. They are very similar to standard arrays with the
exception that they have multiple sets of square brackets after the array identifier.
Example
int [ , ] salary = new int [ , ] { { 1, 25000 }, { 2, 30000} }
Jagged Array
Jagged arrays are called array of arrays. A jagged array is an array of arrays, and therefore its
elements are reference types and are initialized to null.
Example
int[][] jaggedArray =
{
C# .Net Basics
new int[] { 3, 5, 7 },
new int[] { 1, 0, 2, 4, 6 }
};
Fields, properties, methods, and events on a class are collectively referred to as class
members.
Objects
Objects are instances of the class that holds different data in properties/fields and can
interact with other objects. Objects can be created by using the new keyword followed by
the name of the class that the object will be based on.
Class Objects
Fruit Apple
Orange
Grape
Example: Class
public class Fruit
{
Public String Color;
}
Example: Class
{
C# .Net Basics
apple.Color = “Red”;
orange.Color = “Orange”;
Console.WriteLine(apple.Color);
Console.WriteLine(myObj2.Color);
Example: Class
public class Fruit
{
public String Color;
public Fruit()
{
Color = “Yellow”;
}
}
Example: Class
public class Fruit
{
public String Color;
2.3.2 Properties
Properties in C# and .NET have various access levels that is defined by an access modifier.
Properties can be read-write, read-only, or write-only. The read-write property implements
both, a get and a set accessor. A write-only property implements a set accessor, but no get
accessor. A read-only property implements a get accessor, but no set accessor.
Example: Properties
public class Fruit
{
private string color;
}
}
2.3.3 Methods
A method is a block of code which only runs when it is called. We can pass data, known as
parameters, into a method. Methods are used to perform certain actions, and they are also
known as functions. A method is defined with the name of the method, followed by
parentheses (). A method can be called multiple times.
Methods can return a value to the caller. If the return type is not void, the method can
return the value by using the return statement. A statement with the return keyword
followed by a value that matches the return type will return that value to the method caller.
Example: Methods
public class Calculation
{
}
C# .Net Basics
}
2.3.4 Access Modifiers
Access modifiers are keywords used to specify the declared accessibility of a member or a
type. This section introduces the five access modifiers:
public
protected
internal
private
file
The following seven accessibility levels can be specified using the access modifiers:
2.3.5 Encapsulation
Encapsulation is the concept of wrapping data into a single unit. It collects data members
and member functions into a single unit called class. The purpose of encapsulation is to
prevent alteration of data from outside. This data can only be accessed by getter functions
of the class.
Example: Encapsulation
Namespace StudentManagement
{
public class Student
{
}
}
2.3.6 Inheritance
C# .Net Basics
Inheritance is one of the fundamental attributes of object-oriented programming. It allows
you to define a child class that reuses (inherits), extends, or modifies the behaviour of a
parent class. The class whose members are inherited is called the base class. The class that
inherits the members of the base class is called the derived class.
C# and .NET support single inheritance only. That is, a class can only inherit from a single
class. However, inheritance is transitive, which allows you to define an inheritance hierarchy
for a set of types. In other words, type D can inherit from type C, which inherits from type B,
which inherits from the base class type A. Because inheritance is transitive, the members of
type A are available to type D.
Example: Inheritance
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
2.3.7 Polymorphism
Polymorphism is a Greek word that means multiple forms or shapes. You can use
polymorphism if you want to have multiple forms of one or more methods of a class with
the same name.
Compile Time Polymorphism
Inheritance allows you to inherit a base class into a derived class and all the public members
of the base class automatically become members of the derived class. However, you can
redefine the base class's member in the derived class to provide a different implementation
than the base class. This is called method overriding that also known as runtime
polymorphism.
Use the virtual keyword with a member of the base class to make it overridable, and use
the override keyword in the derived class to indicate that this member of the base class is
being redefined in the derived class
2.3.8 Interface
An interface defines a contract. Any class or struct that implements that contract must
provide an implementation of the members defined in the interface. An interface may
define a default implementation for members.
An interface can be defined using the interface keyword. An interface can contain
declarations of methods, properties, indexers, and events.
Example: Interface
interface IFile
{
void ReadFile();
void WriteFile(string text);
}
2.3.9 Abstract
An abstract class is an incomplete class or special class we can't be instantiated. The
purpose of an abstract class is to provide a blueprint for derived classes and set some rules
what the derived classes must implement when they inherit an abstract class.
An abstract class can inherit from a class and one or more interfaces.
An abstract class can implement code with non-Abstract methods.
An Abstract class can have modifiers for methods, properties etc.
An Abstract class can have constants and fields.
An abstract class can implement a property.
An abstract class can have constructors or destructors.
An abstract class cannot support multiple inheritance
Example: Abstract
abstract class Fileoperation
{
public abstract void ReadFile();
public abstract void WriteFile(string text);
2.3.10 Classes
Static Class
C# .Net Basics
A static class is basically the same as a non-static class, but there is one difference: a static
class cannot be instantiated. In other words, we cannot use the new operator to create a
variable of the class type. Because there is no instance variable, we access the members of a
static class by using the class name itself.
The static member is callable on a class even when no instance of the class has been
created. The static member is always accessed by the class name, not the instance name.
Static methods and properties cannot access non-static fields. Static methods can be
overloaded but not overridden, because they belong to the class, and not to any instance of
the class.
Partial Class
Partial Class can break the functionality of a single class into many files. When the
application is compiled, these files are then reassembled into a single class file. The partial
keyword is used to build a partial class.
Sealed Class
A sealed class, is a class that cannot be inherited by any class but can be instantiated. Sealed
classes are used to restrict the inheritance feature of object-oriented programming.
C# .Net Basics
Example: Delegates
delegate int AddNumbers(int value1, int value2);
We can assign a reference to any method that matches the delegate's signature.
Example: Delegates
delegate double MathCalculation(float value1, float value2)
Calling the method referenced by a delegate is called invoking the delegate. We can do this
with the Invoke method.
The delegate can point to multiple methods. A delegate that points multiple methods is
called a multicast delegate. The "+" or "+=" operator adds a function to the invocation list,
and the "-" and "-=" operator removes it.
class Program
{
static void Main(string[] args)
{
MyDelegate del1 = ClassA.MethodA;
MyDelegate del2 = ClassB.MethodB;
2.4.2 Events
An event is a notification sent by an object to signal the occurrence of an action.
The class who raises events is called Publisher, and the class who receives the notification is
called Subscriber. There can be multiple subscribers of a single event.
An event is an encapsulated delegate. It is dependent on the delegate. The delegate defines
the signature for the event handler method of the subscriber class.
1. Declare a delegate.
2. Declare a variable of the delegate with event keyword.
C# .Net Basics
Example: Events
2.5 Collections
C# collection types are designed to store, manage and manipulate similar data more
efficiently. Data manipulation includes adding, removing, finding, and inserting data in the
collection.
Collections provide a more flexible way to work with groups of objects. Unlike arrays, the
group of objects you work with can grow and shrink dynamically as the needs of the
application change.
Types of Collections:
Generic Collections
List
Dictionary
SortedList
Stack
Queue
Non-Generic Collections
ArrayList
HashTable
SortedList
Stack
Queue
Interface Purpose
IEnumerable Enumerates through a collection using a foreach statement.
ICollection Implemented by all collections to provide the CopyTo( ) method
as well as the Count, ISReadOnly, ISSynchronized,
and SyncRoot properties.
IComparer Compares two objects held in a collection so that the collection
C# .Net Basics
can be sorted.
IList Used by array-indexable collections.
IDictionary For key/value-based collections such
as Hashtable and SortedList.
IDictionaryEnumerator Allows enumeration with foreach of a collection that
supports IDictionary.
Example: Generics
class DataStore<T>
{
public T Data { get; set; }
}
T is called type parameter, which can be used as a type of fields, properties, method
parameters and return types. We can also define multiple type parameters separated by a
comma.
We can create an instance of generic classes by specifying an actual type in angle brackets.
class DataStore<T>
{
public void Print(T data)
{
Console.WriteLine(data);
}
}
2.6.2 LINQ
Language-Integrated Query (LINQ) is a powerful set of technologies based on the integration
of query capabilities directly into the C# language. The LINQ provides a consistent query
experience to query objects (LINQ to Objects), relational databases (LINQ to SQL), and XML
(LINQ to XML).
LINQ is a structured query syntax built in C# and VB.NET to retrieve data from different
types of data sources such as collections, ADO.Net DataSet, XML Docs, web service and MS
SQL Server and other databases.
// Data source
string[] names = {"Bill", "Steve", "James", "Mohan" };
// LINQ Query
var myLinqQuery = from name in names
where name.Contains('a')
select name;
// Query execution
foreach(var name in myLinqQuery)
Console.Write(name + " ");
The lambda operator => divides a lambda expression into two parts. The left side is the
input parameter and the right side is the lambda body.
LINQ use Lambda expression (syntax) to execute query (function).
C# .Net Basics
Example: Lambda
// Data source
string[] names = {"Bill", "Steve", "James", "Mohan" };
1
System.IO.IOException
Handles I/O errors.
2
System.IndexOutOfRangeException
Handles errors generated when a method refers to an array index out
of range.
3
System.ArrayTypeMismatchException
Handles errors generated when type is mismatched with the array
type.
4
System.NullReferenceException
Handles errors generated from referencing a null object.
5
System.DivideByZeroException
C# .Net Basics
6
System.InvalidCastException
Handles errors generated during typecasting.
7
System.OutOfMemoryException
Handles errors generated from insufficient free memory.
8
System.StackOverflowException
Handles errors generated from stack overflow.
2.7.2 Try...Catch...Finally
Syntax
try
{
// put the code here that may raise exceptions
}
catch
{
// handle exception here
}
finally
{
// final cleanup code
}
try block: Any suspected code that may raise exceptions should be put inside a try{ } block.
During the execution, if an exception occurs, the flow of the control jumps to the first
matching catch block.
catch block: The catch block is an exception handler block, where you can perform some
action such as logging and auditing an exception. The catch block takes a parameter of an
exception type using which you can get the details of an exception.
finally block: The finally block will always be executed whether an exception raised or not.
Usually, a finally block should be used to release resources, e.g., to close any stream or file
objects that were opened in the try block.
C# .Net Basics
2.7.3 Multiple Catch statements
We can use multiple catch blocks with the different exception type parameters. Multiple
catch blocks are useful when you want to handle different types of exceptions in different
ways.
try
{
int num = int.Parse(Console.ReadLine());
Set a breakpoint and start the debugger. Breakpoints are an essential feature of
reliable debugging. We can set breakpoints where you want Visual Studio to pause
your running code so we can look at the values of variables or the behavior of
memory, or know whether or not a branch of code is getting run.
While paused on the statement, hover over the variable to see a data tip.
To advance the debugger to the next statement, select F10, or choose the Step
Over button in the Debug toolbar, or choose Debug > Step Over from the menu bar.
F10 advances the debugger without stepping into function or methods, although
their code still executes.
To stepping into Functions or Methods, select F11, or choose the Step Into button
from the Debug toolbar, or choose Debug > Step Into from the menu bar. F11 helps
you examine the execution flow of your code in more depth.
To leave the method, select Shift+F11, or choose the Step Out button in the Debug
toolbar, or choose Debug > Step Out from the menu bar.
To rerun your app from the beginning in the debugger, select Ctrl+Shift+F5, or
choose the Restart button in the Debug toolbar, or choose Debug > Restart from the
menu bar.
3 Web Application
ASP.NET is a server-side technology used for developing dynamic websites and web
applications. It is the latest version of Active Server Pages which Microsoft developed for
building dynamic applications.
Features of MVC :
It provides a clear separation of business logic, Ul logic, and input logic.
It offers full control over your HTML and URLs which makes it easy to design web
application architecture.
It is a powerful URL-mapping component using which we can build applications that
have comprehensible and searchable URLs.
It supports Test Driven Development (TDD).
Model:
The model classes represent domain-specific data and business logic in the MVC application.
It represents the shape of the data as public properties and business logic as methods.
In the ASP.NET MVC Application, all the Model classes must be created in the Model folder.
View:
The View component is used for all the UI logic of the application. It generates a user
interface for the user. Views are created by the data which is collected by the model
component but these data aren’t taken directly but through the controller. It only interacts
with the controller.
Controller:
The controller is the component that enables the interconnection between the views and
the model so it acts as an intermediary. The controller doesn’t have to worry about handling
data logic, it just tells the model what to do. It processes all the business logic and incoming
requests, manipulate data using the Model component and interact with the View to render
the final output.
C# .Net Basics
3.3 MVC Application Execution process
All the public methods of the Controller class are called Action methods. They are like any
other normal methods with the following restrictions:
Every controller can have a default action method as per the configured route in
the RouteConfig class.
C# .Net Basics
3.5 URL Routing
Route defines the URL pattern and handler information. All the configured routes of an
application stored in RouteTable and will be used by the Routing engine to determine
appropriate handler class or file for an incoming request.
The ActionVerbs selector is to handle different type of Http requests. The MVC framework
includes HttpGet, HttpPost, HttpPut, HttpDelete, HttpOptions, and HttpPatch action verbs.
You can apply one or more action verbs to an action method to handle different HTTP
requests. If you don't apply any action verbs to an action method, then it will handle
HttpGet request by default.
The ActionResult class is a base class of all the above result classes, so it can be the return
type of action method that returns any result listed above. However, you can specify the
appropriate result class as a return type of action method.
3.8 Views
A view is used to display data using the model class object. The Views folder contains all the
view files in the ASP.NET MVC application.
A controller can have one or more action methods, and each action method can return a
different view. In short, a controller can render one or more views.
We can create a view for an action method directly from it by right clicking inside an action
method and select Add View.
C# .Net Basics
Select the scaffolding template. Template dropdown will show default templates available
for Create, Delete, Details, Edit, List, or Empty view. Select "List" template because we want
to show the list of students in the view.
The default _ViewStart.cshtml is included in the Views folder. It can also be created in all
other Views sub-folders. It is used to specify common settings for all the views under a
folder and sub-folders where it is created.
Set the Layout property to a particular layout view will be applicable to all the child views
under that folder and its sub-folders.
C# .Net Basics
To create a new layout view in Visual Studio, right-click on the Shared folder -> select Add ->
click on New Item. This will open the Add New Item popup, as shown below.
The ViewBag in ASP.NET MVC is used to transfer temporary data (which is not included in
the model) from the controller to the view.
Internally, it is a dynamic type property of the ControllerBase class which is the base class of
the Controller class.
ViewBag only transfers data from controller to view, not visa-versa. ViewBag values will be
null if redirection occurs.
ViewBag doesn't require typecasting while retrieving values from it. This can throw a
run-time exception if the wrong method is used on the value.
ViewBag is a dynamic type and skips compile-time checking. So, ViewBag property
names must match in controller and view while writing it manually.
ViewData is similar to ViewBag, which transfers data from Controller to View. ViewData is
of Dictionary type, whereas ViewBag is of dynamic type. However, both store data in the
same dictionary internally.
C# .Net Basics
ViewData is a dictionary, so it contains key-value pairs where each key must be a string.
ViewData only transfers data from controller to view, not vice-versa. It is valid only during
the current request.
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.
TempData removes a key-value once accessed, you can still keep it for the subsequent
request by calling TempData.Keep() method.
We can render the partial view in the parent view using the HTML helper
methods: @html.Partial(), @html.RenderPartial(), and @html.RenderAction().
[Log]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
C# .Net Basics
}
Action Filter
Action filters contain logic that is executed before and after a controller action executes. You
can use an action filter, for instance, to modify the view data that a controller action
returns.
Action Filters are custom attributes that provide declarative means to add pre-action and
post-action behavior to the controller's action methods.
Result Filter
If you want to execute logic before or after generating result then use Result filter. This filter
can be applied to the controller or action method.
Result filters are only executed for successful results.
Authorization Filter
Authorization filters allow you to perform authorization tasks for an authenticated user. A
good example is Role based authorization.
Authorization filters are used to authenticate whether the user requested action method in
the controller is authorized to access or not and for validating properties of the request.
Authorization filters run before any other filter.
C# .Net Basics
Authorize Attribute
'Authorize' attribute handles both authentication and authorization. In general, it works
well, with the help of extension to handle AJAX calls elegantly, and to distinguish between
unauthorized users and those who are not logged in
You can apply the Authorize attribute to individual methods as well as the controller class as
a whole. If you add the Authorize attribute to the controller class, then any action methods
on the controller will be only available to authenticated users.
Exception Filter
Exception Filter provides an ability to handle the exception for all the method, controller
classes in one place. Exception filters execute when some of the exceptions are thrown from
an action. The exception can be anything. This is by creating a class that inherits from
IExceptionFilter and FileAttribute interface.
There are two types of State management in ASP net. They are:
Server-side
Client-side
3.17 Validations
It is used to check whether the user input is valid. There is a set of validation that is easy-to-
use and at the same time, it is also a powerful way to check for errors and, if necessary,
display messages to the user.
There are two types of validation they are as follows Server side and client-side validation
3.17.1 Model Validations
Model validation is the process of checking whether the user input is suitable for model
binding and if not, it should provide useful error messages to the user. The first part is to
ensure that only valid entries are made.
3.17.2 Data Annotations
The following table lists all the data annotation attributes which can be used for validation.
Attribute Usage
Required Specifies that a property value is required.
C# .Net Basics
Attribute Usage
StringLength Specifies the minimum and maximum length of characters that are allowed
in a string type property.
Range Specifies the numeric range constraints for the value of a property.
RegularExpression Specifies that a property value must match the specified regular expression.
CreditCard Specifies that a property value is a credit card number.
CustomValidation Specifies a custom validation method that is used to validate a property.
EmailAddress Validates an email address.
FileExtension Validates file name extensions.
MaxLength Specifies the maximum length of array or string data allowed in a property.
MinLength Specifies the minimum length of array or string data allowed in a property.
Phone Specifies that a property value is a well-formed phone number.
Entity Framework supports multiple platforms like Windows, Linux, and macOS.
From the Tools menu, choose NuGet Package Manager, and then select choose
Package Manager Console.
Install-Package EntityFramework
Example: DBContext
using System.Data.Entity;
public class BankAccContext : DbContext
{
public BankAccContext()
C# .Net Basics
{
}
If you are using the EF code first approach then there are more ways to initialize the
database provided by the Entity Framework as follows:
1. DropCreateDatabaseAlways.
This database initializer class always drops and creates a new database, whether it is
already present or not with every run of the application.
2. DropCreateDatabaseWhenModelChanges.
This database initializer class drops the existing database and re-creates it if there is a
mismatch between the model classes and table schema.
3. CreateDatabaseIfNotExists.
This class creates a database only if it doesn't exist. It avoids any accidental deletion of
the database.
1. Added
2. Modified
3. Deleted
4. Unchanged
5. Detached
The Context not only holds the reference to all the entity objects as soon as retrieved from
the database, but also keeps track of entity states and maintains modifications made to the
properties of the entity. This feature is known as Change Tracking.
EF API builds and executes the INSERT, UPDATE, and DELETE commands based on the state
of an entity when the context.SaveChanges() method is called. It executes the INSERT
command for the entities with Added state, the UPDATE command for the entities with
Modified state and the DELETE command for the entities in Deleted state. The context does
not track entities in the Detached state.
3.18.7 Mapping Classes to Tables
Code-First will create the database tables with the name of DbSet properties in the context
class.
3.18.8 Mapping Properties to Columns
A Column Map provides specifications that are needed to match or exclude columns from
processing. A Convert, Create, Insert, Load, Restore, or multi-table Compare Request must
reference a Table Map, which might reference one or more Column Maps.
The Column attribute is applied to a property to specify the database column that the
property should map to when the entity's property name and the database column name
differ.
public class Book
{
public int BookId { get; set; }
[Column("Description")]
public string Title { get; set; }
public Author Author { get; set; }
}
C# .Net Basics
3.18.9 One-to-One Relationships
Entity Framework Core introduced default conventions which automatically configure a
One-to-One relationship between two entities. In EF Core, a one-to-one relationship
requires a reference navigation property at both sides. The
following Student and StudentAddress entities follow the convention for the one-to-one
relationship.
4 Web API
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.
Web API allows access to service data from web browsers, mobile apps, and other
devices.
Web API also supports JSON, XML, and other data formats.
Web API helps develop services that support caching, request/response headers,
versioning, etc.
C# .Net Basics
4.1 Features of C# Web API
1. You will create an asp.net core web API project in the visual studio.
C# .Net Basics
namespace HelloWebAPI.Controller
{
public class HelloController : ApiController
{
public string Get()
{
return "Hello World";
}
}
}
C# .Net Basics
4.3 Test Web API
We can use the following third-party tools for testing Web API.
Fiddler
Postman
Web API Controller is similar to ASP.NET MVC controller. It handles incoming HTTP
requests and send response back to the caller.
Web API controller is a class which can be created under the Controllers folder or any
other folder under your project's root folder. The name of a controller class must end
with "Controller" and it must be derived from System.Web.Http.ApiController class. All
the public methods of the controller are called action methods.
Based on the incoming request URL and HTTP verb (GET/POST/PUT/PATCH/DELETE), Web
API decides which Web API controller and action method.
Web API project includes default WebApiConfig class in the App_Start folder and also
includes Global.asax as shown below.
Web API routing is similar to ASP.NET MVC Routing. It routes an incoming HTTP request to
a particular action method on a Web API controller.
1. Convention-based Routing
2. Attribute Routing
C# .Net Basics
Convention-based Routing
In the convention-based routing, Web API uses route templates to determine which
controller and action method to execute. At least one route template must be added into
route table in order to handle various HTTP requests.
We can configure multiple routes in the Web API using HttpConfiguration object.
C# .Net Basics
4.7 Attribute Routing
Attribute routing is supported in Web API 2. As the name implies, attribute routing uses
[Route()] attribute to define routes. The Route attribute can be applied on any controller
or action method.
Web API includes filters to add extra logic before or after-action method executes. Filters
can be used to provide cross-cutting features such as logging, exception handling,
performance measurement, authentication and authorization.
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. However, System.Web.Http.Filters
includes other interfaces and classes that can be used to create filter for specific purpose.
Example
static void Main(string[] args)
{
CallWebAPIAsync()
.Wait();
}
static asyncTaskCallWebAPIAsync()
{
using(var client = newHttpClient())
{
//Send HTTP requests from here.
}
}
Example
using(var client = newHttpClient())
C# .Net Basics
{
client.BaseAddress = newUri("http://localhost:55587/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept
.Add(newMediaTypeWithQualityHeaderValue("application/json"));
}
Afterwards, we have set the base URL for the HTTP request and set the Accept header. In
this example, I have set Accept header to "application/json" which tells the Server to send
the data into JSON format.
Http GET Request is to get the data from the Web API.
Example
using(var client = newHttpClient())
{
client.BaseAddress = newUri("http://localhost:55587/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(newMediaTypeWithQualityHea
derValue("application/json"));
//GET Method
HttpResponseMessage response =
awaitclient.GetAsync("api/Department/1");
if (response.IsSuccessStatusCode)
{
Departmentdepartment = awaitresponse.Content.ReadAsAsync <
Department > ();
}
else
{
Console.WriteLine("Internal server Error");
}
}
4.11 Authentication
Authentication is the process of identifying the user. For example, one user let’s say James
logs in with his username and password, and the server uses his username and password to
authenticate James.
4.12 Authorization
Authorization is the process of deciding whether the authenticated user is allowed to
perform an action on a specific resource (Web API Resource) or not. For example, James
C# .Net Basics
(who is an authenticated user) has the permission to get a resource but does not have the
permission to create a resource.
5 SOLID Principles
SOLID principles are the design principles that enable us to manage most of the software
design problems. Robert C. Martin compiled these principles in the 1990s. These principles
provide us with ways to move from tightly coupled code and little encapsulation to the
desired results of loosely coupled and encapsulated real needs of a business properly.
This means that every class, or similar structure, in your code should have only one job to
do. Everything in that class should be related to a single purpose.
It ensures that a derived class does not affect the behaviour of the parent class, in other
words, that a derived class must be substitutable for its base class.
6 Design Patterns
Design Patterns in the object-oriented world is a reusable solution to common software
design problems that occur repeatedly in real-world application development. It is a
template or description of how to solve problems that can be used in many situations.
6.1 Factory
Factory Method is a creational design pattern that provides an interface for creating objects
in a superclass, but allows subclasses to alter the type of objects that will be created.
In Factory pattern, we create the object without exposing the creation logic. In this pattern,
an interface is used for creating an object, but let subclass decide which class to instantiate.
The creation of object is done when it is required. The Factory method allows a class later
instantiation to subclasses.
In short, factory method design pattern abstracts the process of object creation and allows
the object to be created at run-time when it is required.
6.2 Builder
Builder pattern builds a complex object by using a step-by-step approach. Builder interface
defines the steps to build the final object. This builder is independent of the object’s
creation process. A class that is known as Director, controls the object creation process.
Moreover, builder pattern describes a way to separate an object from its construction. The
same construction method can create a different representation of the object.
6.3 Singleton
The Singleton design pattern is one of the simplest design patterns. This pattern ensures
that the class has only one instance and provides a global point of access to it. The pattern
ensures that only one object of a specific class is ever created. All further references to
objects of the singleton class refer to the same underlying instance.
6.4 Repository
The Repository Design Pattern in C# mediates between the domain and the data mapping
layers using a collection-like interface for accessing the domain objects. Repository Design
Pattern separates the data access logic and maps it to the entities in the business logic. It
works with the domain entities and performs data access logic. In the Repository pattern,
the domain entities, the data access logic, and the business logic talk to each other using
interfaces. It hides the details of data access from the business logic.
C# .Net Basics
7 Unit Testing
7.1 Fundamentals of Unit Testing
Unit Testing is a type of software testing where individual units or components of a software
are tested. The purpose is to validate that each unit of the software code performs as
expected. Unit Testing is done during the development (coding phase) of an application by
the developers. Unit Tests isolate a section of code and verify its correctness. A unit may be
an individual function, method, procedure, module, or object.
3. On the Configure your new project page, enter a name for your project, and then
select Create.
4. In your unit test project, add a reference to the code under test. To add a reference to
a code project in the same solution:
In Reference Manager, select the Solution node under Projects. Select the
code project you want to test, and then select OK.
The [TestClass] attribute is required on any class that contains unit test
methods that you want to run in Test Explorer.
Each test method that you want Test Explorer to recognize must have
the [TestMethod] attribute.
C# .Net Basics
A test method must meet the following requirements:
It returns void.
The Arrange section of a unit test method initializes objects and sets the value
of the data that is passed to the method under test.
The Act section invokes the method under test with the arranged parameters.
The Assert section verifies that the action of the method under test behaves as
expected. For .NET, methods in the Assert class are often used for verification.
[TestMethod]
public void CheckBalance()
{
// arrange
double currentBalance = 10.0;
double withdrawal = 1.0;
double expected = 9.0;
var account = new CheckingAccount("JohnDoe",
currentBalance);
// act
account.Withdraw(withdrawal);
// assert
Assert.AreEqual(expected, account.Balance);
}
8 Logging in .Net
The Logging API is included in the Microsoft.Extensions.Logging package. The Logging API
does not work as standalone. It works with one or more logging providers that store or
display logs to a particular medium such as Console, Debug, TraceListeners etc. Microsoft
provides logging API as an extension in the wrapper Microsoft.Extensions.Logging which
comes as a NuGet package.
C# .Net Basics
Microsoft.Extensions.Logging includes the necessary classes and interfaces for logging. The
most important are the ILogger, ILoggerFactory, ILoggerProvider interfaces and the
LoggerFactory class.
Log levels indicate the importance or severity of log messages. Built-in log providers include
extension methods to indicate log levels.
Example: Logging
namespace DotnetCoreConsoleApp
{
class Program
C# .Net Basics
{
static void Main(string[] args)
{
ILoggerFactory loggerFactory = new
LoggerFactory().AddConsole((_, __) => true);
ILogger logger =
loggerFactory.CreateLogger<Program>();
logger.LogInformation("Logging information.");
logger.LogCritical("Logging critical information.");
logger.LogDebug("Logging debug information.");
logger.LogError("Logging error information.");
logger.LogTrace("Logging trace");
logger.LogWarning("Logging warning.");
}
}
}
9 GIT
9.1 What is Version Control?
Version control, also known as source control, is the practice of tracking and managing
changes to software code. Version control systems are software tools that help software
teams manage changes to source code over time. As development environments have
accelerated, version control systems help software teams work faster and smarter. They are
especially useful for DevOps teams since they help them to reduce development time and
increase successful deployments.
Git is a version control system used for tracking changes in computer files. It is generally
used for source code management in software development.
Features of Git
Tracks history
Supports non-linear development
Creates backups
Scalable
Supports collaboration
Branching is easier
C# .Net Basics
Distributed development
GitHub is a code hosting platform for version control and collaboration. It lets you and
others work together on projects from anywhere.
Branching is a core concept of source control that allows us to separate your work into
different branches so we can work freely on your source code without affecting anyone
else’s work or the actual code in the main branch.
The main idea behind the Git flow branching strategy is to isolate your work into different
types of branches. There are five different branch types in total:
Main
Develop
Feature
Release
Hotfix
The two primary branches in Git flow are main and develop. There are three types of
supporting branches with different intended purposes: feature, release, and hotfix.
C# .Net Basics
9.5.2 Merge Conflict
A merge conflict is an event that takes place when Git is unable to automatically resolve
differences in code between two commits. Git can merge the changes automatically only if
the commits are on different lines or branches.
There are a few steps that could reduce the steps needed to resolve merge conflicts in Git.
1. The easiest way to resolve a conflicted file is to open it and make any necessary
changes
2. After editing the file, we can use the git add a command to stage the new merged
content
3. The final step is to create a new commit with the help of the git commit
command