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

Net Stack Basics

C# .NET is an object-oriented programming language designed to build secure applications across various platforms. It includes fundamental concepts such as data types, arrays, object-oriented programming principles, and features like encapsulation, inheritance, polymorphism, interfaces, and abstract classes. The document serves as a comprehensive introduction to C# basics, including syntax, data structures, and programming paradigms.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Net Stack Basics

C# .NET is an object-oriented programming language designed to build secure applications across various platforms. It includes fundamental concepts such as data types, arrays, object-oriented programming principles, and features like encapsulation, inheritance, polymorphism, interfaces, and abstract classes. The document serves as a comprehensive introduction to C# basics, including syntax, data structures, and programming paradigms.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 63

C# .

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#.

2.1 Data Types


A data type specifies the size and type of data that a variable can store such as integer,
floating, character etc. To avoid errors, to save time and memory, it is important to use the
correct data type for the corresponding variable.
The most common data types are:

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.

Example: Anonymous Type


var book = new { BookId = 1, BookName: “C# Basics”}

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.

Single Dimensional Array

Syntax to declare an array


datatype[ ] arrayName

 datatype is used to specify the type of elements in the array.


 [ ] specifies the rank of the array. The rank specifies the size of the array.
 arrayName specifies the name of the array.

Example: Declaring an Array


int[ ] salary;
C# .Net Basics
Initializing an Array
Declaring an array does not initialize the array in the memory. When the array variable is
initialized, you can assign values to the array.
Array is a reference type, so you need to use the new keyword to create an instance of the
array
Example: Initializing an Array
int[ ] salary = new int[10];

Assigning values to an Array


Assign values to individual array elements by using the index number.
Example: Assign Values
int[ ] salary = new int[10];
salary[0] = 32000;

Can assign values to an array at the time of declaration.


Example: Create and Initialize an Array
int[ ] salary = new int[ ] { 32000, 15000, 25000, 45000 }

Accessing Array Elements


Can access an array element by referring to the index number.
Example: Accessing Array Elements
int firstSalary = salary[0];

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 }
};

2.3 Object Oriented Programming with C#


OOP – stands for Object Oriented Programming

Object-oriented programming is a way of developing software applications using real-world


terminologies to create entities that interact with one another using objects. Programming
(OOPs) in C# is a design approach where we think in terms of real-world objects rather than
functions or methods
Class
A class is a data structure in C# that combines data variables and functions into a single unit.

Example: Declare a Class


public class Fruit
{
// Fields, properties, methods and events go
here...
}

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

static void Main(string[] args)

{
C# .Net Basics

Fruit apple = new Fruit();

apple.Color = “Red”;

Fruit orange = new Fruit();

orange.Color = “Orange”;

Console.WriteLine(apple.Color);

Console.WriteLine(myObj2.Color);

We can create multiple objects for a class


2.3.1 Constructors
A constructor is a special method of the class which gets automatically invoked whenever an
instance of the class is created. The main use of constructors is to initialize the private fields
of the class while creating an instance for the class. When you have not created a
constructor in the class, the compiler will automatically create a default constructor of the
class.
 The constructor name must match the class name
 A class can have any number of constructors.
 A constructor doesn't have any return type, not even void.

Example: Class
public class Fruit
{
public String Color;

public Fruit()
{
Color = “Yellow”;
}
}

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

Example: Class
public class Fruit
{
public String Color;

public Fruit(string fruitColor)


{
Color = fruitColor;
C# .Net Basics
}
}

2.3.2 Properties

Property in C# is a member of a class that provides a flexible mechanism for classes to


expose private fields. Internally, C# properties are special methods called accessors. A C#
property have two accessors, get property accessor and set property accessor. A get
accessor returns a property value, and a set accessor assigns a new value. The value
keyword represents the value of a property.

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;

public string Color


{
get { return color; }
set { color = value; }

}
}

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
{

public int Add(int x, int y)


{
return x + y;

}
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:

 public: Access isn't restricted.


 protected: Access is limited to the containing class or types derived from the
containing class.
 internal: Access is limited to the current assembly.
 protected internal: Access is limited to the current assembly or types derived from
the containing class.
 private: Access is limited to the containing type.
 private protected: Access is limited to the containing class or types derived from the
containing class within the current assembly.
 file: The declared type is only visible in the current source file. File scoped types are
generally used for source generators.

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
{

public string ID { get; set; }


public string Name { get; set; }
public string Email { get; set; }

}
}

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; }

public string GetFullName(){


return FirstName + " " + LastName;
}
}

class Employee : Person


{
public int EmployeeId { get; set; }
public string CompanyName { get; set; }

Employee emp = new Employee();


emp.FirstName = "Steve";
emp.LastName = "Jobs";
emp.EmployeeId = 1;
emp.CompanyName = "Apple";

var fullname = emp.GetFullName(); //Steve


Jobs

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

Compile-time polymorphism is also known as method overloading. C# allows us to define


more than one method with the same name but with different signatures.
C# .Net Basics
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.

Example: Method Overloading


class StringPrinter
{
public void Print(string str) {
Console.WriteLine(str);
}

public void Print(string str1, string str2){


Console.WriteLine($"{str1}, {str2}");
}

public void Print(string str1, string str2, string


str3){
Console.WriteLine($"{str1}, {str2}, {str3}");
}
}

Run Time Polymorphism

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


overriding.

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

 A method, property, indexer, or event can be overridden in the derived class.


 Static methods cannot be overridden.
 Must use virtual keyword in the base class methods to indicate that the methods can
be overridden.
 Must use the override keyword in the derived class to override the base class
method.

Example: Method Overriding


class Person
C# .Net Basics
{
public virtual void Greet()
{
Console.WriteLine("Hi! I am a person.");
}
}

class Employee : Person


{
public override void Greet()
{
Console.WriteLine("Hello! I am an employee.");
}
}

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.

 An interface cannot contain constructors and fields.


 Interface members are by default abstract and public.
 Implement interface explicitly using InterfaceName.MemberName.
 An interface can inherit one or more interfaces.

Example: Interface
interface IFile
{
void ReadFile();
void WriteFile(string text);
}

class FileInfo : IFile


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

public void WriteFile(string text)


{
Console.WriteLine("Writing to file");
}
C# .Net Basics
}

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);

void WriteDB(string text)


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

class FileInfo : Fileoperation


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

Public override void WriteFile(string text)


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

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.

Syntax: Static Class


static class classname
{
//static data members
//static methods
}

Static Members and Static Methods

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.

Example: Partial Class – Employee1.cs


public partial class Employee
{
public void DoWork()
{
}
}

Example: Partial Class – Employee2.cs


public partial class Employee
{
public void TakeRest()
{
}
}

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: Sealed class


sealed class Employee
{
public string EmployeeName;
public int EmployeeAge;
}

public class MarketingEmployee : Employee // Throws an error

2.3.11 Class Libraries and Namespace


Class Library is a major entity of the .NET Framework. This library gives the program access
to runtime environment. The class library consists of lots of prewritten code that all the
applications created in .NET will use. The code for all the elements like forms, controls
actually comes from the class library.
A namespace is designed for providing a way to keep one set of names separate from
another. The class names declared in one namespace does not conflict with the same class
names declared in another.
The using keyword states that the program is using the names in the given namespace

2.4 Delegates and Events


2.4.1 Delegates
A delegate is a type that represents a method with a specific signature and return type.
The declaration of a delegate looks exactly like the declaration of a method, except with the
keyword delegate in front of it.

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)

public static class Calculator


{
public static double AddNumbers(float value1, float value2)
{
return value1 + value2;
}

public static double DivideNumbers(float value1, float value2)


{
return value1 / value2;
C# .Net Basics
}
}

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.

Example: Multicast Delegate


public delegate void MyDelegate(string msg); //declaring a delegate

class Program
{
static void Main(string[] args)
{
MyDelegate del1 = ClassA.MethodA;
MyDelegate del2 = ClassB.MethodB;

MyDelegate del = del1 + del2; // combines del1 + del2


del("Hello World");

MyDelegate del3 = (string msg) => Console.WriteLine("Called


lambda expression: " + msg);
del += del3; // combines del1 + del2 + del3
del("Hello World");

del = del - del2; // removes del2


del("Hello World");

del -= del1 // removes del1


del("Hello World");
}
}

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.

An event can be declared in two steps:

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

2.5.1 Collection Interfaces


.NET framework provides interfaces that implement by collections in language to provide
the functionality of iterating over objects in the collection, adding and removing an object
from collection to randomly access an object from the collection. Different interfaces
provide a different set of functionalities.

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.

2.5.2 Concurrent collections


System.Collections. Concurrent namespace has several collection classes that are thread-
safe and scalable. These collections are called concurrent collections because they can be
accessed by multiple threads at a time.
Concurrent collections can be
shared across multiple threads with no explicit locks and it also increases the
scalability and performance of multi-threaded operations.
Below are the different types of concurrent collections:
ConcurrentDictionary<TKey,TValue>
ConcurrentStack<T>
ConcurrentQueue<T>
ConcurrentBag<T>
BlockingCollection<T>
2.6 Generics
Generics allow you to define the specification of the data type of programming elements in
a class or a method, until it is actually used in the program.
Generic classes are defined using a type parameter in an angle brackets after the class
name.

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.

Example: Instantiating Generic Class

DataStore<string> store = new DataStore<string>();


C# .Net Basics

We can specify different data types for different objects.

Example: Generic Class

DataStore<string> strStore = new DataStore<string>();


strStore.Data = "Hello World!";
//strStore.Data = 123; // compile-time error

DataStore<int> intStore = new DataStore<int>();


intStore.Data = 100;

 Generics increase the reusability of the code.


 Generics are type-safe.
 Generic has a performance advantage because it removes the possibilities of boxing
and unboxing.

2.6.1 Generic Methods


A method declared with the type parameters for its return type or parameters is called a
generic method.

Example: Generic Method

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.

Example: LINQ Query


C# .Net Basics

// 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 + " ");

2.6.3 Lambda Expressions


Lambda expressions are anonymous functions that contain expressions or sequence of
operators. All lambda expressions use the lambda operator =>, that can be read as “goes to”
or “becomes”. The left side of the lambda operator specifies the input parameters and the
right side holds an expression or a code block that works with the entry parameters.

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" };

List<string> result = names.Select( x => x.ToUpper());

2.7 Exception Handling


An exception is a problem that arises during the execution of a program.
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.
2.7.1 System.Exception Class
C# exceptions are represented by classes. The exception classes in C# are mainly directly or
indirectly derived from the System.Exception class. Example:
System.ApplicationException and System.SystemException classes.

S.N Exception Class & Description


o.

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

Handles errors generated from dividing a dividend with zero.

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.

Example: Multiple catch blocks

try
{
int num = int.Parse(Console.ReadLine());

int result = 100 / num;

Console.WriteLine("100 / {0} = {1}", num, result);


}
catch(DivideByZeroException ex)
{
Console.Write("Cannot divide by zero. Please try again.");
}
catch(InvalidOperationException ex)
{
Console.Write("Invalid operation. Please try again.");
}
catch(FormatException ex)
{
Console.Write("Not a valid format. Please try again.");
}
catch(Exception ex)
{
Console.Write("Error occurred! Please try again.");
}
}

2.7.4 Debugging Techniques


Debugging is the process of finding errors during application execution. It does not mean
syntax errors, with which the application cannot be compiled, but on logic errors.
 To start the debugger, select F5, or choose the Debug Target button in the Standard
toolbar, or choose the Start Debugging button in the Debug toolbar, or
choose Debug > Start Debugging from the menu bar.
C# .Net Basics
 To stop the debugger, select Shift+F5, or choose the Stop Debugging button in the
Debug toolbar, or choose Debug > Stop Debugging from the menu bar.

 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.

 Navigate code and inspect data by using data tips

 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.

3.1 ASP .Net MVC Architecture


The Model-View-Controller (MVC) framework is an architectural/design pattern that
separates an application into three main logical components Model, View, and Controller.
C# .Net Basics
Each architectural component is built to handle specific development aspects of an
application. It isolates the business logic and presentation layer from each other.

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).

3.2 Model, Views and Controller


C# .Net Basics

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

 User will make page request.


 Route.Config of requested page will get checked on Controller.
 Page initialization will be performing on Model and after page initialization one
result set will get generated.
 Generated Result set will be getting delivered to the Controller from Model.
 Result set will get validated (Page Validation) and after page validation Result set will
get delivered to View through view engine.

3.4 Controllers and Action Methods


The Controller in MVC architecture handles any incoming URL request. The Controller is a
class, derived from the base class System.Web.Mvc.Controller. Controller class contains public
methods called Action methods. Controller and its action method handles incoming browser
requests, retrieves necessary model data and returns appropriate responses.

All the public methods of the Controller class are called Action methods. They are like any
other normal methods with the following restrictions:

 Action method must be public. It cannot be private or protected


 Action method cannot be overloaded
 Action method cannot be a static method.

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.

3.6 Action verbs

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 following table lists the usage of HTTP methods:

Http Method Usage


GET To retrieve the information from the server. Parameters will be
appended in the query string.
POST To create a new resource.
PUT To update an existing resource.
HEAD Identical to GET except that server do not return the message body.
OPTIONS It represents a request for information about the communication
options supported by the web server.
DELETE To delete an existing resource.
PATCH To full or partial update the resource.
C# .Net Basics
3.7 ActionResult
MVC framework includes various Result classes, which can be returned from an action
method. The result classes represent different types of responses, such as HTML, file, string,
JSON, javascript, etc. The following table lists all the result classes available in ASP.NET MVC.

Result Class Description


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

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.

3.9 Layout Views


An application may contain a specific UI portion that remains the same throughout the
application, such as header, left navigation bar, right bar, or footer section. ASP.NET MVC
introduced a Layout view which contains these common UI portions so that we don't have
to write the same code in every page. The layout view is the same as the master page of the
ASP.NET webform application.
C# .Net Basics

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.

3.10 View Bag

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.

3.11 View Data

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.

3.12 Temp Data

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.

3.13 HTML Helpers


The HtmlHelper class renders HTML controls in the razor view. It binds the model object to
HTML controls to display the value of model properties into those controls and also assigns
the value of the controls to the model properties while submitting a web form. So always
use the HtmlHelper class in razor view instead of writing HTML tags manually.

Extension Method Strongly Typed Method HTML Control


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

3.14 Partial Views


A partial view is a reusable portion of a web page. It is .cshtml or .vbhtml file that contains
HTML code. It can be used in one or more Views or Layout Views. You can use the same
partial view at multiple places and eliminates the redundant code.
C# .Net Basics
To create a partial view, right click on the Shared folder -> click Add -> click View.. to open
the Add View popup, as shown below.

We can render the partial view in the parent view using the HTML helper
methods: @html.Partial(), @html.RenderPartial(), and @html.RenderAction().

3.15 Action Filters


Action filter executes before and after an action method executes. Action filter attributes
can be applied to an individual action method or to a controller. When an action filter is
applied to a controller, it will be applied to all the controller's action methods.

We can create a custom action filter in two ways, first, by implementing


the IActionFilter interface and the FilterAttribute class. Second, by deriving
the ActionFilterAttribute abstract class.

The IActionFilter interface include following methods to implement:

 void OnActionExecuted(ActionExecutedContext filterContext)


 void OnActionExecuting(ActionExecutingContext filterContext)

The ActionFilterAttribute abstract class includes the following methods to override:

 void OnActionExecuted(ActionExecutedContext filterContext)


 void OnActionExecuting(ActionExecutingContext filterContext)
 void OnResultExecuted(ResultExecutedContext filterContext)
 void OnResultExecuting(ResultExecutingContext filterContext)
C# .Net Basics
Example: Custom ActionFilter for Logging

public class LogAttribute: ActionFilterAttribute


{
public override void OnActionExecuted(ActionExecutedContext
filterContext)
{
Log("OnActionExecuted", filterContext.RouteData);
}

Public override void OnActionExecuting(ActionExecutingContext


filterContext)
{
Log("OnActionExecuting", filterContext.RouteData);
}

public override void OnResultExecuted(ResultExecutedContext


filterContext)
{
Log("OnResultExecuted", filterContext.RouteData);
}

public override void OnResultExecuting(ResultExecutingContext


filterContext)
{
Log("OnResultExecuting ", filterContext.RouteData);
}

private void Log(string methodName, RouteData routeData)


{
var controllerName = routeData.Values["controller"];
var actionName = routeData.Values["action"];
var message = String.Format("{0}- controller:{1} action:{2}",
methodName,
controllerName, actionName);
Debug.WriteLine(message);
}
}

Example: ActionFilter on Controller

[Log]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
C# .Net Basics
}

public ActionResult About()


{
return View();
}

public ActionResult Contact()


{
return View();
}
}

There are four different types of filters:

1. Authorization filters – Implements the IAuthorizationFilter attribute.


2. Action filters – Implements the IActionFilter attribute.
3. Result filters – Implements the IResultFilter attribute.
4. Exception filters – Implements the IExceptionFilter attribute.

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.

3.16 State Management


State management in ASP NET is an object and preserves type state control. This is because
ASP NET applications are basically stateless. In ASP NET, the information of users is stored
and maintained till the user session ends.
Types of State Management in ASP.NET:

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.

3.17.3 Custom Validation


A custom validation attribute lets you create metadata that you can use in the data model
to validate data fields. You must derive the custom attribute from the ValidationAttribute
base class.
This validation can be added for both the client side and the server side. You understand
that decorating the properties in a model with an Attribute can make that property eligible
for Validation
3.17.4 Client Validation
When you enter data, the browser and/or the web server will check to see that the data is
in the correct format and within the constraints set by the application. Validation done in
the browser is called client-side validation
Client-side validation is visible to the user. It involves having validation on input forms
through JavaScript. For example, if the input is submitted for a phone number or email, a
JavaScript validator would provide an error if anything is submitted that does not conform
to a phone number or email.

3.18 Entity Framework


Entity framework is an Object Relational Mapping (ORM) framework that offers an
automated mechanism to developers for storing and accessing the data in the database.
Developers can work with data in domain-specific objects and properties, such as customers
and customer addresses, without worrying about the underlying database tables and
columns where this data is kept.

 Entity Framework is a lightweight and extensible object-relational mapping (ORM)


technology.
C# .Net Basics

 Entity Framework supports multiple platforms like Windows, Linux, and macOS.

 Entity Framework supports both relational and non-relational data sources.

 Entity Framework makes it easier for programmers to perform create, read,


update and delete (CRUD) operations by supporting databases.

 C# Entity Framework allows us to configure the Entity Framework model through


data annotation properties.

 C# Entity Framework provides a series of migration commands that can be run


from the NuGet Package Manager Console or the Command Line Interface.

3.18.1 Code First Approach


Code-First is mainly useful in Domain Driven Design. In the Code-First approach, you focus
on the domain of your application and start creating classes for your domain entity rather
than design your database first and then create the classes which match your database
design.

Code first work flow

3.18.2 Database First Approach


This approach is an alternative for the code-first approach and the model-first approach. It
creates the model and codes from the database in the project and connects them with the
database and developer.
C# .Net Basics
3.18.3 Installation of EF

 From the Tools menu, choose NuGet Package Manager, and then select choose
Package Manager Console.

 Enter the following command in the Package Manager Console window:

Install-Package EntityFramework

3.18.4 DBContext Class in Entity Framework


The DBContext class is basically used by our application to interact with the underlying
database. That means this class is used to manage the database connection as well as also
used to perform CRUD operation with the underlying database.
In order to use the DbContext class in your application, you need to create a class derives
from the DbContext class.
In order to perform any useful task by the DbContext class, we need an instance of
the DbContextOptions class. The instance of the DbContextOptions carries all the required
configuration information such as the connection string, database provider, etc.
An entity is a class in an Entity Framework that maps the database tables.

Example: DBContext

using System.Data.Entity;
public class BankAccContext : DbContext
{
public BankAccContext()
C# .Net Basics
{
}

public DbSet<AccHolder> Accountholder { get; set; }


}

3.18.5 Code First Migrations


Code First Migrations allow you to create a new database or update an existing database
based on your model classes using the Package Manager Console for running commands.

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.

 Open Package Manager Console


 Run Enable-Migrations command in a Package Manager console.
 This command added two more classes to your project in the Migrations folder.
1.201411061912454_InitialCreate.cs
 This migration was generated because Code First already created a database for us
before we enabled migrations
1.Configuration.cs
 It allows you to configure how Migrations behave for your context.
 Update the database with the new changes we made in the model.
 Run Add-Migration MigrationForRoleInEmp in a Package Manager console.
 Now it adds one more class to the Migrations folder in MigrationForRoleInEmp.cs.
Let's use Update-Database to apply this migration to the database.
 Run the Update-Database command in a Package Manager console.
C# .Net Basics
3.18.6 Entity State
EF API maintains the state of each entity during its lifetime. Each entity has a state based on
the operation performed on it via the context class. The entity state represented by an
enum in Microsoft.EntityFrameworkCore.EntityState in EF Core with the following values:

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.

Example: One to One Relationship


public class Student
{
public int Id { get; set; }
public string Name { get; set; }

public StudentAddress Address { get; set; }


}

public class StudentAddress


{
public int StudentAddressId { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }

public int StudentId { get; set; }


public Student Student { get; set; }
}

3.18.10 LINQ to Entities


The DbSet class is derived from IQuerayable. So, we can use LINQ for querying
against DbSet, which will be converted to an SQL query. EF API executes this SQL query to
the underlying database, gets the flat result set, converts it into appropriate entity objects
and returns it as a query result.
LINQ Extension Methods
First()
FirstOrDefault()
Single()
SingleOrDefault()
ToList()
Count()
Min()
Max()
Last()
LastOrDefault()
Average()
C# .Net Basics
Example: LINQ
using (var ctx = new SchoolDBEntities())
{
var student = ctx.Students
.Where(s => s.StudentName == "Bill")
.FirstOrDefault<Student>();
}

3.18.11 Using Order by and Where Clause


Use the OrderBy operator with ascending/descending keywords in LINQ query syntax to get
the sorted entity list.

Example: LINQ Order By


using (var ctx = new SchoolDBEntities())
{
var students = ctx.Students.OrderBy(s =>
s.StudentName).ToList();
// or descending order
Var descStudents = ctx.Students.OrderByDescending(s =>
s.StudentName).ToList();
}

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 aids in the development of lightweight, maintainable web services.

 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

4.2 Implementation of C# Web API

1. You will create an asp.net core web API project in the visual studio.
C# .Net Basics

3. Create a “Models” folder to store the schema for the project.

4. Add a Web API Controller. It will be an empty controller.


C# .Net Basics

5. We need to add action methods

Example: Web API


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

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

4.4 Web API Controller

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.

4.5 Configure Web API


Web API supports code based configuration. It cannot be configured in web.config file.
We can configure Web API to customize the behaviour of Web API hosting infrastructure
C# .Net Basics
and components such as routes, formatters, filters, DependencyResolver,
MessageHandlers, ParamterBindingRules, properties, services etc.

Web API project includes default WebApiConfig class in the App_Start folder and also
includes Global.asax as shown below.

4.6 Web API Routing

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.

Web API supports two types of routing:

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.

Example: Web API with Default Route


public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Enable attribute routing
config.MapHttpAttributeRoutes();
// Add default route using convention-based routing
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}

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.

Example: Attribute Routing


public class StudentController : ApiController
{
[Route("api/student/names")]
public IEnumerable<string> Get()
{
return new string[] { "student1",
"student2" };
}
}

4.8 Media-Type Formatters


Media type formatters are classes responsible for serializing request/response data so
that Web API can understand the request data format and send data in the format which
client expects.
Web API includes following built-in media type formatters.

Media Type Formatter Class


JsonMediaTypeFormatter
XmlMediaTypeFormatter
FormUrlEncodedMediaTypeFormatter
JQueryMvcFormUrlEncodedFormatter

4.9 Web API Filters

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

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: Web API Filter Class


public class LogAttribute : ActionFilterAttribute
{
public LogAttribute()
{
C# .Net Basics
}

public override void OnActionExecuting(HttpActionContext


actionContext)
{
// On Executing
}

public override void


OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
// On Executed
}
}

4.10 Consuming Web APIs


HttpClient class provides a base class for sending/receiving the HTTP requests/responses
from a URL. It is a supported async feature of .NET framework. HttpClient is able to process
multiple concurrent requests. It is a layer over HttpWebRequest and HttpWebResponse. All
methods with HttpClient are asynchronous.
To call Web API methods from the console Application, the first step is to install the
required packages, using NuGet Package Manager. The following package needs to be
installed in the Application.
Install-Package Microsoft.AspNet.WebApi.Client
Next step is to create HttpClient object. In the following code snippet, the main function
calls private static method "CallWebAPIAsync" and this blocks until CallWebAPIAsync
completes the process, using wait function.

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

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.

SOLID is an acronym of the following.

 S: Single Responsibility Principle (SRP)


 O: Open closed Principle (OCP)
 L: Liskov substitution Principle (LSP)
 I: Interface Segregation Principle (ISP)
 D: Dependency Inversion Principle (DIP)

5.1 Single-responsibility Principle


SRP says "Every software module should have only one reason to change".

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.

5.2 Open-closed Principle


The Open/closed Principle says "A software module/class is open for extension and closed
for modification".

5.3 Liskov Substitution Principle


The Liskov Substitution Principle (LSP) states that "you should be able to use any derived
class instead of a parent class and have it behave in the same manner without
modification".

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.

5.4 Interface Segregation Principle


The Interface Segregation Principle states "that clients should not be forced to implement
interfaces they don't use. Instead of one fat interface, many small interfaces are preferred
based on groups of methods, each one serving one submodule.".
Like classes, each interface should have a specific purpose/responsibility (refer to SRP). You
shouldn't be forced to implement an interface when your object doesn't share that purpose.
C# .Net Basics
5.5 Dependency Inversion Principle
The Dependency Inversion Principle (DIP) states that high-level modules/classes should not
depend on low-level modules/classes. Both should depend upon abstractions. Secondly,
abstractions should not depend upon details. Details should depend upon abstractions.

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.

7.2 Loosely Coupled and Testable Code


Testable code refers to the loosely coupled code where code does not directly depend on
internal/external dependencies, so we can easily replace the real dependencies (sometimes referred
to as real service) with mock services in test cases.

7.3 Test Driven Development


What Test Driven Development is

 Development or programming practice that adds the reliability to the Application


behavior.
 Mindset and approach towards software development that enforces writing Unit Tests
before/along with coding the functionality.
 Enforces an interface based design to support loose coupling and modularity.
 Enforces a check that is done by our code; what we intended?

Why Test-Driven Development is important

 Many projects fail because they lack good testing methodology.


 Helps the developers by enforcing better design and sense of confidence in terms of
quality by regularly checking and looking the test cases execution success. It also helps
to avoid break in another dependent area due to any recent changes.
 Helps Testers by saving their time from logging obvious issues and re-validation, so
that they can focus on the complex test scenarios.
 Helps Project Managers in optimizing the overall budget by having reduced test cycles
and less issues at UAT and Production.
 Helps the client by better overall experience and reduced maintenance cost later.
 Helps the company in getting repeat business as a result of client satisfaction.
 Appears natural practice but in reality, it isn’t that common.

7.3.1 Creating Test Project


To create a unit test project

1. On the File menu, select New > Project, or press Ctrl+Shift+N.


C# .Net Basics
2. On the Create a new project page, type unit test into the search box. Select the
project template for the test framework that you want to use, for example MSTest
Test Project or NUnit Test Project, and then select Next.

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:

 Select the test project in Solution Explorer.

 On the Project menu, select Add Reference.

 In Reference Manager, select the Solution node under Projects. Select the
code project you want to test, and then select OK.

7.3.2 Test Classes and Methods

A test class must meet the following requirements:

 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's decorated with the [TestMethod] attribute.

 It returns void.

 It cannot have parameters.

7.3.3 Arrange, Act and Assert


The AAA (Arrange, Act, Assert) pattern is a common way of writing unit tests for a method
under test.

 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.

Example: Arrange, Act, Assert

[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.

8.1 Logging Providers


A logging provider displays or stores logs to a particular medium such as a console, a
debugging event, an event log, a trace listener, and others. Microsoft provides various
logging providers as NuGet packages.

The following table lists important logging providers.

Logging Provider’s NuGet Package Output target


Microsoft.Extensions.Logging.Console Console
Microsoft.Extensions.Logging.AzureAppServices Azure App Services 'Diagnostics logs'
and 'Log stream' features
Microsoft.Extensions.Logging.Debug Debugger Monitor
Microsoft.Extensions.Logging.EventLog Windows Event Log
Microsoft.Extensions.Logging.EventSource EventSource/EventListener
Microsoft.Extensions.Logging.TraceSource Trace Listener
8.2 Log Levels

Log levels indicate the importance or severity of log messages. Built-in log providers include
extension methods to indicate log levels.

The following table lists log levels in .NET Core.

Log Level Severity Extension Method Description


Trace 0 LogTrace() Logs messages only for tracing purposes
for the developers.
Debug 1 LogDebug() Logs messages for short-term debugging
purposes.
Information 2 LogInformation() Logs messages for the flow of the
application.
Warning 3 LogWarning() Logs messages for abnormal or
unexpected events in the application flow.
Error 4 LogError() Logs error messages.
Critical 5 LogCritical() Logs failures messages that require
immediate attention.

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.

9.2 What is Git?

Git is a version control system used for tracking changes in computer files. It is generally
used for source code management in software development.

 Git is used to tracking changes in the source code


 The distributed version control tool is used for source code management
 It allows multiple developers to work together
 It supports non-linear development through its thousands of parallel branches

Features of Git

 Tracks history
 Supports non-linear development
 Creates backups
 Scalable
 Supports collaboration
 Branching is easier
C# .Net Basics
 Distributed development

9.3 Git Basic Concepts

 Create a "repository" (project) with a git hosting tool (like Bitbucket)


 Copy (or clone) the repository to your local machine
 Add a file to your local repo and "commit" (save) the changes
 "Push" your changes to your main branch
 Make a change to your file with a git hosting tool and commit
 "Pull" the changes to your local machine
 Create a "branch" (version), make a change, commit the change
 Open a "pull request" (propose changes to the main branch)
 "Merge" your branch to the main branch

9.4 Introduction to GitHub

GitHub is a code hosting platform for version control and collaboration. It lets you and
others work together on projects from anywhere.

 Git is not the same as GitHub.


 GitHub makes tools that use Git.
 GitHub is the largest host of source code in the world, and has been owned by
Microsoft since 2018

9.5 Git Branching

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.

9.5.1 Common Branching Strategy

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.

The following is an example of how a Git merge conflict works:

How to Resolve Merge Conflicts in Git?

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

4. Git will create a new merge commit to finalize the merge


C# .Net Basics

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy