You are on page 1of 39

C# .

NET
Introduction to C#
• History of C# -
• C# was designed by Anders Hejlsberg from Microsoft in 2000 and was
later approved as an international standard by Ecma (ECMA-334) in 2002
and ISO (ISO/IEC 23270) in 2003. (Ecma - European Computer
Manufacturers Association is a non-profit organization that develops
standards in computer hardware, communications, and programming
languages.)
• It was introduced with .NET Framework 1.0 (NET is a software framework
which is designed and developed by Microsoft. It is a virtual machine for
compiling, debugging, executing programs written in different languages
like C#, VB.Net etc.)
• It is based on C++ and Java, but it has many additional features.
• C# is strongly typed and fully object-oriented.
• It was developed by Microsoft to compete with JAVA.
• It has an important feature- Write once run anywhere.

• .NET Platform - platform for building many different types of applications. With .NET,
you can use multiple languages, editors, and libraries to build different types of
applications - web, mobile, desktop, games, and IoT. It is a model where applications
can be built as reusable components and are sharable over the internet. A model
that encourages applications to be shared as a "service" (web services). It is a model
that enables true "interoperability" wherein the language used is only a matter of
choice, thus enabling organizations to take advantage of existing skill sets.

• .NET is a cross-platform .NET implementation for different applications on


Windows, Linux, and macOS.

• .NET Framework supports websites, services, desktop apps etc. on


Windows.

• Xamarin is a .NET implementation for mobile operating systems.

Key Components include:


• MS Intermediate Language: all code is compiled into a more abstract,
trimmed version before execution. All .NET languages are compiled to MSIL –
the common language of .NET.
A language-specific compiler converts the source code to the
intermediate language. This intermediate language is then
converted into the machine code by the Just-In-Time (JIT) compiler.
• The CLR- common language runtime; responsible for executing MSIL code
• Just-In-Time compiler (JIT) is a part of Common Language Runtime (CLR)
which is responsible for managing the execution of .NET programs regardless
of .NET programming language. The JIT compiler requires less memory
usage as only the methods that are required at run-time are compiled
into machine code by the JIT Compiler.
• .Net Framework Class Library – contains a huge library of reusable types,
classes, interfaces, structures, enumerations, collections etc.
• Common Language Specification - contains the specifications for the .Net
supported languages and implementation of language integration.
• ASP.NET is the Framework exposed to the web for building web applications,
using IIS to manage simple pages of code so that they can be complied into
full .NET programs. These generate HTML for the browser.
• Common Type System - It provides guidelines for declaring, using, and
managing types at runtime, and cross-language communication.
• Metadata and Assemblies - Metadata is the binary information describing the
program, which is either stored in a portable executable file (PE) or in the
memory. It provides information like types, properties, fields base classes etc.
Assembly is a logical unit consisting of the assembly manifest, type metadata,
IL code and set of resources like image files etc.
• Windows Forms - This contains the graphical representation of any window
displayed in the application.
• AJAX is an extension of ASP.Net for developing and implementing AJAX
functionality. ASP.Net AJAX contains the components that allow the developer
to update data on a website without a complete reload of the page.
• ADO .Net - It is the technology used for working with data and databases. It
provides accesses to data sources like SQL server, OLE DB, XML etc. The
ADO .Net allows connection to data sources for retrieving, manipulating, and
updating data.
• Windows Presentation Foundation - It provides a separation between the user
interface and the business logic. It helps in developing visually stunning
interfaces using documents, media, two and three dimensional graphics,
animations and more.
• Windows Communication Foundation (WCF) - It allows you to create a
service that exposes a Web endpoint. Web endpoints send data by XML or
JSON, there is no SOAP envelope. The only way to ensure security of a Web
endpoint is to expose it through HTTPS protocol.
• LINQ - It imparts data querying capabilities to .Net languages using a syntax
which is like the traditional query language SQL.

• Documentation and Selected Books – Visit the following web site -


https://docs.microsoft.com/en-us/dotnet/
Selected Books for C# -
• C# 8.0 and .NET Core 3.0 HYPERLINK "https://geni.us/ygBLl" HYPERLINK
"https://geni.us/ygBLl" HYPERLINK "https://geni.us/ygBLl"– HYPERLINK
"https://geni.us/ygBLl" HYPERLINK "https://geni.us/ygBLl" HYPERLINK
"https://geni.us/ygBLl" Modern cross-platform development: Build applications
with C#

• Programming C# 8.0 (O’Reilly)

• Trends in development of C# and .NET - .NET Core is one of the most widely
used development frameworks by businesses.
• .NET Core framework includes- ASP.NET, C#, ML.NET(Machine Learning
Framework), AOT(ahead-of-time compilation in Angular app), GC(Garbage
Collector-manages the allocation and release of memory), Runtime, JIT, Base
Class Library, Entity Framework, WinForms, VB.NET, F#, WPF, and Xamarin.
• NET Core 3.1 is lighter and faster, which makes it best for cloud installations,
where speed is important.
• MVC 1.0 /.NET Framework 3.5
• . NET Framework 4.8 is the last version.
• C# 10.0 is the latest version
• .NET 6.0 is the latest version

C# Data Types - A data type specifies the size and type of variable values.
Data type Size Description
int 4 bytes Whole nos.
long 8 bytes Whole nos.
float 4 bytes Decimal nos.
double 8 bytes Decimal nos.
bool 1 bit True/false
char 2 bytes Single character
string 2 bytes per character Sequence of characters
Example-
int a=5;
double sal=4500.10;
char Ans=’Y’;
bool married=true;
string name =”Gauri”;

C# Operators - C# has rich set of built-in operators and provides the following type of
operators −

• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc. Operators
Arithmetic Operators -
Operator Example
+(Addition) A+B
- (Subtraction) A-B
*(Multiplication) A*B
/(Division – Quotient of A/B
Division)
%(Modulus – Remainder of A%B
Division)
++(Increment Operator) If A=10, A++=11
--(Decrement Operator) If A=10, A--=9

Relational Operators -
Operator Description Example

== Checks if two operands are equal (A == B)

!= Checks if two operands are equal or (A != B)


not

> Greater than (A > B)


< Less than (A < B)

>= Greater than or Equal To. (A >= B)

<= Less than or Equal To. (A <= B)

Logical Operators –
Operator Description Example

&& AND operator - If both the operands are non zero then (A && B)
condition becomes true.

|| OR Operator - If any of the two operands is non zero (A || B)


then condition becomes true.

! NOT Operator - Use to reverses the logical state of its !(A &&
operand. If a condition is true then Logical NOT operator B)
will make false.

Bitwise Operators –
a B a&b a|b a^b

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume if A = 60; and B = 13; then in the binary format they are as follows −

A = 0011 1100

B = 0000 1101

Then

A&B = 0000 1100


A|B = 0011 1101

A^B = 0011 0001

~A  = 1100 0011

The Bitwise operators. Assume variable A holds 60 and variable B holds 13, then –

Examples-
Operato Description Example
r

& Binary AND Operator (A & B) = 12, which is 0000 1100

| Binary OR Operator (A | B) = 61, which is 0011 1101

^ Binary XOR Operator (A ^ B) = 49, which is 0011 0001

~ Binary Ones Complement Operator (~A ) = -61, which is 1100 0011


is unary and has the effect of in 2's complement due to a
'flipping' bits. signed binary number.

<< Binary Left Shift Operator. The left


operands value is moved left by the
A << 2 = 240, which is 1111 0000
number of bits specified by the right
operand.

>> Binary Right Shift Operator. The left


operands value is moved right by
A >> 2 = 15, which is 0000 1111
the number of bits specified by the
right operand.

Miscellaneous Operators -
Examples -
Operato Description Example
r

sizeof() Returns the size of a data type. sizeof(int), returns 4.

typeof() Returns the type of a class. typeof(StreamReader);


Object Serialization – Serialization in C# is the process of converting an object into a
stream of bytes, so that one can store the object to memory, a database, or a file.
Purpose is to save the state of an object to be able to recreate it when needed. The
reverse process is called deserialization.
Example solved.
Data Collections - Collection classes are specialized classes for data storage and
retrieval. These classes include stacks, queues, lists, and hash tables. Most collection
classes implement the same interfaces.
• Simple List – Allows you to create a list of items and then lets you iterate
through it – List<string>
// Create a list of strings.
var fruits = new List<string>();
fruits.Add("chickoo");
fruits.Add("apple");
fruits.Add("grapes");
fruits.Add("guava");

// Iterate through the list.


foreach (var fruit in fruits)
{
Console.Write(fruit + " ");
}

var fruits = new List<string>();{“chickoo”,”apple”,”grapes”,”guava”};


fruits.Remove(“chickoo”);
// Iterate through the list.
foreach (var fruit in fruits)
{
Console.Write(fruit + " ");
}

• Generic List
private static void GenericList()
{
var Details = new List< PersonalDetails>
{
new PersonalDetails () { Name="Gauri", Age=50},
new PersonalDetails () { Name="John", Age=25},
new PersonalDetails () { Name="Jack", Age=10},
new PersonalDetails () { Name="Linda", Age=3}
};

foreach (PersonalDetails detail in Details)


{
Console.WriteLine(detail.Name + " " + detail.Age);
}

public class PersonalDetails


{
public string Name { get; set; }
public int Age { get; set; }
}
Following table lists some of the System.Collections classes-

ArrayList an array of objects whose size is dynamically increased as and


when required.
Queue a first in, first out (FIFO) collection of objects.
HashTable a collection of key/value pairs that are organized based on the
hash code of the key.
Stack a last in, first out (LIFO) collection of objects.
• Hash codes are indices generated for the keys and values are retrieved using the
keys in collections. Keys may be of any type but hash code will be integer.
Example to understand between List and ArrayList –
ArrayList arrayList = new ArrayList();
arrayList.Add(“C#”);
arrayList.Add(100); //not strongly typed

List<string> myArray = new List<string>();


myArray.Add(“C#”);
myArray.Add(100); // strongly typed
int sum=0;
foreach(int i in myArray)
{sum += i; }

Following table lists some of the System.Collections.Generic classes-


Dictionary a collection of key/value pairs that are organized
based on the key.
List a list of objects that can be accessed by index.
Provides methods to search, sort, and modify lists.
Queue a first in, first out (FIFO) collection of objects.
SortedList a collection of key/value pairs that are sorted by key
based on the
associated IComparer<T> implementation.
Stack a last in, first out (LIFO) collection of objects.

Instruction Flow Control –


• Conditional Statements –
• If..else..else if..

Syntax if (condition)

// block of code to be executed if the condition is True

if (condition)

// block of code to be executed if the condition is True

else

// block of code to be executed if the condition is False

if (condition1)

// block of code to be executed if condition1 is True

else if (condition2)
{

// block of code to be executed if the condition1 is false and


condition2 is True

else

// block of code to be executed if the condition1 is false and


condition2 is False

Ternary Operator - variable = (condition) ? expressionTrue :


expressionFalse;

• switch…case
switch (expression)
{
  case constant-expression:
     statement
     jump-statement
  default:
     statement
     jump-statement
}
• while loop
while(condition)
{
// block of code to be executed
}
• for loop

for (statement 1; statement 2; statement 3)


{

// code block to be executed

Statement 1 – initialization- is executed (one time) before the


execution of the code block.

Statement 2  - condition - defines the condition for executing


the code block.

Statement 3 – evaluation - is executed (every time) after the


code block has been executed.

foreach (type variableName in arrayName)

// code block to be executed

continue in loops - Basically, it skips statements defined after


the keywork(continue) and continues with the next iteration of
the loop.

Data Table - The DataTable class in C# ADO.NET is a database table representation


and provides a framework of columns and rows to store data in a grid form. It is an in-
memory table. You typically use the DataTable class to perform any disconnected data
access.
OOPs concepts
Class : It is a blueprint or template of an object. It is a generic representation of an
object that defines all the attributes and behaviour of an object. It is also defined as a
user defined data type. Examples – Vehicle, Employee, Payslip etc.
Object : It is anything that physically or logically exists. Object belongs to a class and
hence possess all the attributes and behaviour of that class to which it belongs to.
Examples – Car, Rectangle, Cat etc.
Encapsulation : It is a process of wrapping both the members/variables and functions
into a single entity/unit i.e. in a class.
Abstraction : Data is secured since it is declared within a class and has private access
modifier. Only the functions of the class are public so that they can access the
members. Here implementation details are hidden, it is not necessary to know the
details of how the function is written, we just need to call/execute the functions.
Access Specifiers -
• Public -- Accessible outside the class through object reference.
• Private -- Accessible only through member functions.
• Protected -- Just like private but Accessible in derived classes also through
member Functions, in case of inheritance.
• Internal -- Visible inside the assembly. Accessible through objects.
• Protected Internal -- Visible inside the assembly and in derived classes outside
the assembly through member functions.
Constructor : It is used to create objects and initialize the variables/members of the
class. It returns a reference to the object, so it does not have a return type, but it can
have a list of parameters.
Inheritance : It is an essential feature of object oriented programming, since it allows us
to reuse existing code. It defines IS-A relationship between a Base class and Derived
class. Common attributes and functions can be defined in a Base class and can be
reused further by the derived classes, so that they can define their own/specific
attributes and functions instead of redefining them again. C# does not support Multiple
inheritance of classes.
Note: Classes can inherit from multiple interfaces at the same time and not from
multiple classes.
Abstract Class/Method :The abstract modifier indicates the incomplete
implementation.
Abstract Method: A method which is declared abstract, has no “body” or
implementation within a class and declared inside the abstract class only. An
abstract method must be implemented in all non-abstract classes or derived
classes using the override keyword.
Important Points: 
• Generally, we use abstract class with inheritance.
• A user must use the override keyword before the method in child class, the
abstract class is used to inherit in the child class.
• An abstract class cannot be inherited by structures.
• It can contain constructors or destructors.
• It can implement functions with non-Abstract/concrete methods.
• It cannot support multiple inheritance.
• It can’t be static.

Interface - Interface in C# is a blueprint of a class and cannot be instantiated.


It is like abstract class because all the methods which are declared inside the
interface are abstract methods
It is used to achieve multiple inheritance which can't be achieved by class.
Its implementation must be provided by class or struct. The class or struct which
implements the interface, must provide the implementation of all the methods
declared inside the interface.
Interface cannot have instance members as we cannot create object of an interface,
hence we cannot initialize the members of the interface.
Interface must have "public" access specifier, but methods are by default public. The
classes that implement the Interfaces must have the "public" access specifier for the
methods.
Polymorphism : It means multiple forms. A particular task can be done in many ways,
but the action/task is same, for e.g. Add method in a class can add two numbers, also
can add to dates, arrays, objects, strings etc. So the purpose is same, but it is achieved
in many different ways.
Compile time Polymorphism is attained by overloading methods. By defining methods
with the same name but having different parameters and return types.
Runtime Polymorphism is achieved using inheritance by overriding method of a base
class in a derived class. By overriding the methods in the derived class we can change
the behaviour of the methods of a base class in the derived class.
Understanding Basic Program Structure in C#

Since C# is an object-oriented programming language, a program consists of


various objects that interact with each other by means of methods and perform
calculations and tasks specified within the methods/actions. It is mandatory to write
the entire code within a class.

Important Points –

• In C#, class cannot be defined as private, the default scope is internal

• Class members are private by default


For example, let us consider a Rectangle class, it may consist of attributes like
length and width and has a method for calculating area and display details.
using System;
namespace RectangleApp
{
class Rectangle
{
// variables
double length;
double width;
public void GetDetails()
{
length = 4.5;
width = 3.5;
}
public double CalcArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", CalcArea());
}
}

Class RectangleDemo
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}

C# Array of Objects - Array is a group of elements of similar data types. Object array is
a group of elements of a user defined data type i.e. a class. Hence it can contain
elements of different data types too.
Error Handling exceptions – An exception is an error that arises during the execution
of a program at runtime. A C# exception is a response to an exceptional circumstance
that arises while a program is running, such as an attempt to divide by zero or Array
index out of bound. Exceptions provide a way to transfer control from one part of a
program to another instead of crashing the program.
C# exception handling is built upon four keywords: try, catch, finally, and throw.

• try − It identifies a block of code for which exceptions are handled. The
statements that most likely cause an error are defined in try block. It is followed
by one or more catch blocks.

• catch − A program catches an exception with an exception handler at the place


in a program where you want to handle the problem. The catch keyword
indicates the catching of an exception.

• finally − The finally block is used to execute a given set of statements, whether
an exception is thrown or not thrown. For example, if you open a file, it must be
closed or close the database connection.

• throw − A program throws an exception when a problem shows up. This is done
using a throw keyword.
Exception Classes in C# - C# exceptions are defined as classes. The exception
classes in C# are mainly directly or indirectly derived from
the System.Exception class.

Examples of predefined Exception classes are –


System.DivideByZeroException - Handles errors generated from dividing a dividend
with zero.

System.IO.IOException - Handles I/O errors.

System.IndexOutOfRangeException - Handles errors generated when a method refers


to an array index out of range.

C# Input/Output - A file is a sequence of characters stored on the disk and when it


is opened in the memory of the computer for reading or writing it becomes a
stream. There are two main streams: the input stream and the output stream.
The input stream is used for reading data from file/source (read operation) and
the output stream is used for writing into the file /destination(write operation).
C# I/O Classes : The System.IO namespace has various class that are used for
performing various operation with files, like creating and deleting files, reading from or
writing to a file, closing a file, creating directories etc.
• The FileStream Class : The FileStream class in the System.IO namespace
helps in reading from, writing to and closing binary files. This class is derived
from the abstract base class Stream. You need to create a FileStream object
to create a new file or open an existing file
• StreamReader/StreamWriter : The StreamReader and StreamWriter classes
are used for reading from and writing data to text files. These classes are
derived from the abstract base class Stream, which supports reading and
writing characters into a file stream
File.ReadAllText - This method is used to read all the lines in a file at once. The lines
are then stored in a string variable. 
String path = @"C:\Gauri\DotNet\Test.txt";
String lines;
lines = File.ReadAllText(path);
Console.WriteLine(lines);

File.ReadAlllines - The method is used to read all the lines one by one in a file. The
lines are then stored in a string array variable .
String path = @"C:\Gauri\DotNet\Test.txt";
String[] linesArray;
lines = File.ReadAllLines(path);

Console.WriteLine(linesArray[0]);
Console.WriteLine(linesArray[1]);

File.Copy - The method is used to make a copy of an existing file . 

String path = @"C:\Gauri\DotNet\Test.txt";


String copypath = @"C:\Gauri\DotNet\NewTest.txt";
File.Copy(path,copypath);

File.Delete – The method is used to Delete existing file.

String path = @"D:\Example.txt";


File.Delete(path);

Debugging Applications
• Set a breakpoint and start the debugger - Breakpoints are a useful feature
when you know the line of code or the section of code that you want to examine
in detail at runtime. To debug, you need to start your app with the debugger
attached to the app process. F5 (Debug > Start Debugging) is the most common
way to do that.
• Stepping Through Code - To start your app with the debugger attached,
press F11 (Debug > Step Into). F11 is the Step Into command and advances the
app execution one statement at a time. When you start the app with F11, the
debugger breaks on the first statement that gets executed. When you are on a
line of code that is a function or method call, you can press F10 (Debug > Step
Over) instead of F11. F10 advances the debugger without stepping into functions
or methods in your app code (the code still executes). By pressing F10, you can
skip over code that you're not interested in. This way, you can quickly get to code
that you are more interested in. 
• Debug Windows – The Autos and Locals windows show variable values while
you are debugging. The windows are only available during a debugging session.
The Autos window shows variables used around the current breakpoint.
The Locals window shows variables defined in the local scope, which is usually
the current function or method.
To open the Autos window, while debugging, select Debug > Windows > Autos
To open the Locals window, while debugging, select Debug > Windows > Locals
• Watch Windows – We can inspect the global/local variables by adding them in
the Watch window
• Call stack - You can view the function/procedure calls that are currently on the
stack. The Call Stack window shows the order in which methods and functions
are getting called.

ASP .NET
ASP.Net Introduction – It is a server-side technology for building Data driven Web
applications/Web Sites.
Understanding Project Structure –
• Assembly Info -stores information about the name, title, version etc. of
the Assembly
• App_Start - The App_Start folder is used to contain the class files
which are needed at the time the application starts. The classes like
BundleConfig, RouteConfig, etc. are stored within this folder.
• RouteConfig -Used to setup the Startup Page, the Routes can be
defined in the Global.asax file’s “Application_Start” event.
• BunleConfig - Bundling is a new feature in ASP.NET 4.5 that makes
it easy to combine or bundle multiple files into a single file. We can
bundle CSS, JavaScript and other bundles. Fewer files cause fewer
HTTP requests and that can improve first page load performance.
• The ViewSwitcher control allows the end user of the site to switch
between the “desktop” view of a page and the “mobile” view of the
page.
• Master Page defines the theme for all pages of the web site.
• Web.config – We can define Database Connections, Session settings
etc. here, these parameters are set when the Web site is loaded.

Server side events - An event is an action or occurrence such as a mouse click, a key
press, mouse movements, or any system-generated notification.
Events in ASP.NET raised at the client side(browser), and handled at the server level.
For example, a user clicks a button in the browser, a Click event is raised. The browser
handles this client-side event by posting the Page to the server. The server has a
subroutine describing what to do when the event is raised; it is called the event-handler.
Therefore, when the event message is transmitted to the server, it checks whether the
Click event has an associated event handler. If it has, the event handler is executed.
Application and Session Events
The most important application events are:

• Application_Start - It is raised when the application/website is started.

• Application_End - It is raised when the application/website is stopped.

Similarly, the most used Session events are:

• Session_Start - It is raised when a user first request a page from the


application.

• Session_End - It is raised when the user logs out of the application.

ASP.NET server controls are also used for functions, like validation, data access,
security, creating master pages, and data manipulation.

ASP.NET uses five types of web controls, which are:

• HTML controls
• HTML Server controls
• ASP.NET Server controls
• ASP.NET Ajax Server controls
• User controls and custom controls
ASP.NET server controls are the primary controls used in ASP.NET. These controls can
be grouped into the following categories:

• Validation controls - These are used to validate user input and they work by
running client-side script.

• Data source controls - These controls provide data binding to different data
sources.

• Data view controls - These are various lists and tables, which can bind to data
from data sources for displaying.

• Login and security controls - These controls provide user authentication.

• Master pages - These controls provide consistent layout and interface


throughout the application.

• Navigation controls - These controls help in navigation. For example, menus,


tree view etc.

• Rich controls - These controls implement special features. For example,


AdRotator, FileUpload, and Calendar control.

ASP.NET server controls are derived from the WebControl class and inherit all the
properties, events, and methods of this class - System.Web.UI.Control class.

Project File - To compile an ASP.NET application, the compiler needs information such
as the version of the dotnet framework, the type of the application, etc. A .csproj file
stores all this information that allows dotnet to build and compile the project. An
ASP.NET project can depend on third-party libraries developed by other developers.
Usually, these libraries are installed as Nuget packages using Nuget package manager.
Once you install a package using Nuget, the name of the package along with its version
is listed in the .csproj file.
ASP.NET Page Life Cycle - When a page is requested by the client, it is loaded
into the web server memory, processed, and sent to the browser. Then it is
unloaded from the memory. At each of these steps, methods and events are
created, could be overridden according to the need of the application. In other
words, you can write your own code to override the default behaviour. The Page
class creates a hierarchical tree of all the controls on the page.
Following are the different stages of an ASP.NET page:

• Page request - When client sends a page request, ASP .NET decides whether
to parse and compile the page, or there would be a cached version of the page;
accordingly, the response is sent.

• Starting of page life cycle - At this stage, the Request and Response objects
are set. If the request is an old request or post back, the IsPostBack property of
the page is set to true. The UICulture property of the page is also set.

• Page initialization(Page_PreInit) - At this stage, the controls on the page are


assigned unique ID by setting the UniqueID property and the themes are
applied.

• Page load - At this stage, control properties are set using the view state and
control state values.

• Validation - Validate method of the validation control is called and on its


successful execution, the IsValid property of the page is set to true.

• Postback event handling - If the request is a postback (old request), the


related event handler is invoked.

• Page rendering - At this stage, view state for the page and all controls are
saved. The page calls the Render method for each control and the output of
rendering is written to the OutputStream class of the Response property of
page.

• Unload - The rendered page is sent to the client and page properties, such as
Response and Request, are unloaded and all clean-up done.
IsPostBack is a Boolean property of a page and is set to true after a page is first
loaded. Thus, the first time when the page loads the IsPostBack flag is false and for
subsequent PostBacks, it is true. An important point is that each time a PostBack
occurs, the entire page including the Page_Load is executed.
State Management - State management is done at client side and server side.
Client Side: It can achieved with the help of View state, Cookies, Query String, hidden
fields  and control state.
SessionID enables you to retrieve the unique session identifier of a particular user.
ByDefault ASP.Net SessionID is stored in cookies. SessionID is stored in a cookie
named ASP.NET_SessionId to identity a user. If a user disables cookies in the browser,
then Session state doesn’t work. The ASP.NET_SessionId cookie is used to associate
the correct data with the correct user.
Server Side: with the help of Cache, Application, Session and Database. 
View state is the method that the ASP.NET page framework uses to preserve page and
control values between round trips. It is a Page-Level State Management technique.
View State is turned on by default and normally serializes the data in every control on
the page regardless of whether it is used during a post-back.
Master page allows you to create a consistent look and Feel for all the pages in your
web application/web site. Master Page Design is common for all the pages. Master
page consists of two pieces, the master page itself and one or more content pages. A
master page is an ASP.NET file with. Master extension.  ContentPlaceholder control,
which defines a region on the master page, is where the content pages can plug in page
specific content.

WebPage Navigation - The Navigation Controls are useful for maintaining the page


hierarchy as well as the page navigation in ASP.Net. There are three navigation controls
that one can use in ASP.Net 2.0 and above. These controls are:
• SiteMapPath - You can use a site map to describe the logical structure of
your site. You can then manage page navigation by modifying the site map
as pages are added or removed, instead of modifying hyperlinks in all
Web pages.
• Menu
• TreeView
Whenever we have an application that expects user input, then it becomes important
to ensure the validity of the data input by the user. For example you don’t want that
the user leave some field empty or null. There are scenarios when the user data
must be in some particular format example email ID. There could be scenarios when
we want the data to be in some range example date input.
So, for all the above mentioned scenarios, if we take the user input without
validation, then chances are that we will end up having wrong data with us (perhaps
in database).
Types of Validation -
There are two ways we can perform validation:
• Client-side validation

• Server-side validation

Client-Side Validation
Client-side validation is something that will happen on users' browser. The validation
will occur before the data gets posted back to server. It is a good idea to have client-
side validation as the user gets to know what needs to be changed immediately, i.e.,
no trips to servers are made. So, from the users' point of view, it gives him fast
response and from the developers' point of view, it saves valuable resources of
server.
JavaScript is the most widely used to perform client-side validation. From decades,
developers have been using JavaScript for client side validation. It is always a good
idea to have knowledge of JavaScript as it gives us full control over client-side
validation. Now Microsoft is also embracing jQuery in its current versions so perhaps
JavaScript and/or Jquery should be the right thing to use for client-side validation.
JavaScript provides full control to the developer on how client-side validation should
happen but developers will have to write the validation code themselves. ASP.NET
also provides some validation controls to perform client-side validation which could
help the developers in putting client-side validation in place without writing a lot of
code. These controls will also use JavaSscript underneath to perform validations.
We will see these controls in a moment.
Server-Side Validation
Server-side validation occurs at server. The benefit of having server-side validation
is that if the user somehow bypasses the client-side validation (accidentally or
deliberately), then we can catch the problem on the server side. So having server-
side validation provides more security and ensures that no invalid data gets
processed by the application. Server-side validation is done by writing our custom
logic for validating all the input. ASP.NET also provides us some controls which will
facilitate the server-side validation and provides a framework for the developers to
do the same.
NOTE: Web developer may choose to go with any one type of validation but usually
it is a good idea to have client-side validation and same validation on server side
too. It sure takes some resources of server to validate the already validated data (on
client side) but it ensures security and that is always good.
AJAX is not a new programming language, but a technique for creating better,
faster, and more interactive web applications. With AJAX, your JavaScript can
communicate directly with the server, using the JavaScript XMLHttpRequest object.
With this object, your JavaScript can trade data with a web server, without reloading
the page. AJAX uses asynchronous data transfer (HTTP requests) between the
browser and the web server, allowing web pages to request small bits of information
from the server instead of whole pages. The AJAX technique makes Internet
applications smaller, faster, and more user-friendly.
Validation Controls in ASP.NET
The validation controls provided by ASP.NET are:
• RequiredFiledValidator

• CompareValidator

• RangeValidator

• RegularExpressionValidator
• CustomValidator

• ValidationSummary

Some Common properties of validation controls:-


ControlToValidate: ID of the control which should be validated by this control.
ErrorMessage: This message will be displayed to the user when validation fails.
This should always be something which user can read and act upon.
Text: This string will be visible where the validation control is placed when validation
fails. Usually, it is a good idea to set it to "*".
Login controls – The ASP.NET login controls provide a robust login solution for
ASP.NET Web applications with very less programming. By default, login controls
work nicely with ASP.NET membership and forms authentication to help automate
user authentication for a Web site. The Login control displays a user interface for
user authentication. The Login control contains text boxes for the user name and
password and a check box that allows users to indicate whether they want the
server to store their identity using ASP.NET membership and automatically be
authenticated/remembered the next time they visit the site.
*To save passwords in browser - Settings > Autofill > Passwords.
Themes and Skins - A theme is a collection of property settings that allow you to give
uniform look and feel for pages and controls, and then apply the look consistently
across pages in a Web application, across an entire Web application, or across all Web
applications on a server. Themes are made up of a set of elements: skins, cascading
style sheets (CSS), images, and other resources. Themes are defined in special
directories in your Web site or on your Web server. You can define themes for a single
Web application, or as global themes that can be used by all applications on a Web
server.
A skin file has the file name extension .skin and contains property settings for individual
controls such as button, text box or label controls. You can define skins in a separate file
for each control or define all the skins for a theme in a single file.  
User Control - A User Control is a reusable page or control with an extension of .ascx
and is created like an .aspx page but the difference is that a User Control does not
render on its own, it requires an .aspx page to be rendered as a container.
User Controls are reusable components. Suppose we need a calendar control in the
application with some custom requirements in multiple pages, then instead of creating
the control repetitively you can create it once and use it on multiple pages.

Website Configuration Settings - Web.config files are used to apply configuration


settings to a particular web application. Web.config files are in the application's root
directory or inside a folder situated in a lower hierarchy.

The machine.config file is used to apply configuration settings for all the websites on a
web server.The machine.config is located in the Windows directory Microsoft.Net\
Framework\Version\CONFIG.

There can be multiple web.config files in an application nested at different hierarchies.


However there can be only one machine.config file on a web server.
There are number of important settings that can be stored in the configuration file.
Some of them are -
• Database connections
• Caching settings
• Session States
• Error Handling
• Security
When you initially run your web application, the runtime loads the configuration settings
for your web application in the cache.
• Example - <sessionState timeout="20"></sessionState>//sets session timeout for
20 mins.
You can set the default authentication mode for your website using the mode attribute,
which has the following possible values: Windows, Forms, Passport, None
• <authentication mode="Windows"></authentication>

You can disable debugging in your application by including this code in


the <system.web> section:
 <system.web>

<compilation debug="false"/>

</system.web>

What is IIS?
Internet Information Services (IIS, formerly Internet Information Server) is an
extensible web server created by Microsoft for use with Windows NT family.
IIS supports HTTP, HTTPS, FTP, FTPS, SMTP and NNTP.
• IIS is a protocol server.
• It is implemented as a set of several system services that use the most
common Internet protocols including HTTP, FTP, NTTP and SMTP.
• The Microsoft IIS is built into the Microsoft Windows NT Server operating
system.
Website Deployment –

• msbuild C:\WebDeploy\WebDeploy.sln /p:DeployOnBuild=true

Creates a Package to be deployed inside obj\Debug directory, in which a Zip is


created.

UnZip/Extract this file into some other Folder and deploy it on IIS.

This Zip file will not contain CodeBehind files, only .aspx are available.

ASP .Net Personalization – Web sites are designed for repeated visits from the users.
Personalization allows a site to remember the user identity and other information
details, and it presents an individualistic environment to each user.
Personalized content means that the user is displayed the content based on the
preferences and other known information about the user.
This ability to display personalized content and retrieve information about the user is
known as Personalization. This personalization is provided in ASP.NET by the Profile
service. 
The Profile must be set in Web.config file and can be accessed further in the Code
behind files.

ADO.NET
ADO.NET is the database technology of the .NET platform and is built using Microsoft
ActiveX Data Objects (ADO). The language neutral nature of ADO makes it a powerful
and potent way for .NET platform. ADO.NET is an integral part of the .NET Compact
Framework, providing access to relational data, XML documents, and application data.
ADO.NET supports a variety of development needs. You can create database-client
applications and middle-tier business objects used by applications, tools, languages or
Internet browsers.
ADO.NET defines DataSet and DataTable objects which are optimized for moving
disconnected sets of data across intranets and Internets, including through firewalls. It
also includes the traditional Connection and Command objects, as well as an object
called a DataReader that resembles a forward-only, read-only ADO recordset. If you
create a new application, your application requires some form of data access most of
the time.
Connected Architecture of ADO.NET - The architecture of ADO.net, in which connection
must be opened to access the data retrieved from database is called as connected
architecture. Connected architecture was built on the connection, command, datareader
and transaction classes. Connected architecture is required when you constantly make
trips to the database for any CRUD (Create, Read, Update and Delete) operation you
wish to do. This creates more traffic to the database but is normally much faster as you
should be doing smaller transactions.

Disconnected Architecture in ADO.NET - The architecture of ADO.net in which data


retrieved from database can be accessed even when connection to database was
closed is called as disconnected architecture. Disconnected architecture of ADO.net
was built on classes connection, dataadapter, commandbuilder and dataset and
dataview. Disconnected architecture is a method of retrieving a record set from the
database and storing it giving you the ability to do many CRUD (Create, Read, Update
and Delete) operations on the data in memory, then it can be re-synchronized with the
database when reconnecting. A method of using disconnected architecture is using a
Dataset.

DataReader is Connected Architecture since it keeps the connection open until all
rows are fetched one by one
DataSet is Disconnected Architecture since all the records are brought at once and
there is no need to keep the connection alive
Difference between Connected and disconnected architecture

Connected Disconnected

It is connection oriented. It is disconnection oriented.

Datareader DataSet

Connected methods gives faster Disconnected get low in speed and


performance performance.

connected can hold the data of single disconnected can hold multiple tables
table of data

connected you need to use a read disconnected you cannot


only forward only data reader

Data Reader can't persist the data Data Set can persist the data

It is Readonly, we can't update the We can update data


data.

DataReader - DataReader is used to read the data from database and it is a read and
forward only connection oriented architecture during fetch the data from database.
DataReader will fetch the data very fast when compared with dataset. Generally, we will
use ExecuteReader object to bind data to datareader. To bind datareader data to
gridview we need to write the code like as shown below
protected void BindGridview()
{
using (SqlConnection con = new SqlConnection("Data Source=gauri;Integrated
Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserName,LastName,Location
FROM UserInformation", con);
SqlDataReader dr = cmd.ExecuteReader();
gvUserInfo.DataSource = dr;
gvUserInfo.DataBind();
con.Close();
}
}
DataSet - DataSet is a disconnected orient architecture that means there is no need of
active connections during work with datasets and it is a collection of DataTables and
relations between tables. It is used to hold multiple tables with data. You can select data
form tables, create views based on table and ask child rows over relations. Data Set
provides you with rich features like saving data as XML and loading XML data.
C# Code

// This method is used to bind gridview from database


protected void BindGridview()
{
SqlConnection con = new SqlConnection("Data Source=gauri;Integrated
Security=true;Initial Catalog=MySampleDB");
con.Open();
SqlCommand cmd = new SqlCommand("select UserName,LastName,Location
from UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}

DataAdapter - Data Adapter will acts as a Bridge between DataSet and database. This
data adapter object is used to read the data from database and bind that data to
dataset. Data adapter is a disconnected oriented architecture. Check below sample
code to see how to use Data Adapter in code
C# Code

// This method is used to bind gridview from database


protected void BindGridview()
{
SqlConnection con = new SqlConnection("Data Source=gauripc;Integrated
Security=true;Initial Catalog=MySampleDB");
con.Open();
SqlCommand cmd = new SqlCommand("select UserName,LastName,Location
from UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}

Data Access with LINQ - allows a developer to query data inside in-memory objects,
relational databases, and from XML using a uniform syntax.
LINQ offers the following advantages:
• LINQ offers common syntax for querying any type of data source; for example,
an XML document, SQL database, an ADO.NET dataset, an in-memory
collection, or any other remote or local data source that you have chosen to
connect to and access by using LINQ.
• LINQ bridges the gap and strengthens the connection between relational data
and the object-oriented world.
• LINQ speeds development time by catching many errors at compile time.
• LINQ query expressions (unlike traditional SQL statements) are strongly typed.
LINQ to SQL is a feature for managing and accessing relational data as objects.  It
connects to the database, converts LINQ into SQL, submits and executes the SQL,
transforms results into objects back, and even tracks changes and automatically
requests database updates.
 LINQ query requires three things:
• Entity classes
• A data context
• LINQ queries
*Select Individual components->LINQ to SQL Tools in the Visual Studio Installer.
Exception Handling -
• Adding Try Catch Blocks in a Web Page - If an exception occurs while executing
the logic in a try block, the control is immediately moved to the catch block that
reads the exception message and after catching the exception in the catch block
a user-friendly error can be shown to the end users. Example - Using try and
catch block inside the Page_Load event of a Web Page.

• Page Level Exceptions - ASP.NET Framework has error handling events where
exceptions can be caught. When there is an unhandled error at the code level,
meaning if the code does not have a structured try catch block to handle
exceptions, then that can be handled at the page level. At the page level
“Page_Error” is the event that catches the exception. If an exception is not
handled at the page level, then it will be propagated to the application level in the
global.aspx file, inside “application_Error” event.
Example –
protected void Page_Error(object sender, EventArgs e)  
{  
    Exception Ex = Server.GetLastError();  
    Server.ClearError();  
    Response.Redirect("ErrorPage.aspx");  
}  

void Application_Error(object sender, EventArgs e)  
{  
     // Code that runs when an unhandled error occurs  
    Exception Ex =Server.GetLastError();  
    Server.ClearError();  
    Server.Transfer("Error.aspx");  
}  

• Response.Redirect changes the url in the browser. So, they can be bookmarked.
Whereas Server.Transfer retains the original url in the browser. It just replaces
the contents of the previous page with the new one.
• Response.Redirect involves a roundtrip to the server whereas Server.Transfer
conserves server resources by avoiding the roundtrip. It just changes the focus of
the webserver to a different page and transfers the page processing to a different
page.

• Response.Redirect can be used for both .aspx and html pages whereas
Server.Transfer can be used only for .aspx pages.

• Response.Redirect can be used to redirect a user to an external website.


Server.Transfer can be used only on sites running on the same server. You
cannot use Server.Transfer to redirect the user to a page running on a different
server.
• Custom error pages - Custom error pages are displayed depending on the
ASP.NET HTTP status codes.
It can be defined at two levels.
• Application level(web.Config File)
Example - <customErrors mode="On" defaultRedirect="DefaultError.aspx">  
    <error statusCode="404" redirect="PageNotFound.aspx"/>  
    <error statusCode="500" redirect="ServerError.aspx"/>   
</customErrors> 
The Internal Server Error 500 is a collective status code for server errors.
Therefore, at first glance, it is not possible to determine where the error actually
lies. The user only knows that the server has reported an unexpected error.
The error 404 occurs when the requested page is not found.
• Page Level (At Page directive)
Example - ErrorPage="~/ServerError.aspx" – It works only for that page.
• Tracing - If tracing is enabled, and the page is requested, ASP.NET appends to
the page a series of tables containing execution details about the page request. 
Include Trace="true" in <%@ Page Title="" Language="C#"...%> directive.
Trace modes are of two types –

• SortByCategory: Set TraceMode to SortByTime to sort trace messages in the


order in which they are processed.

• SortByTime: Set TraceMode to SortByCategory to sort trace messages by the


categories.

Tracing at application Level - <trace enable="true" pageOutput="false"


requestLimit="40" localOnly="false"/>

If pageOutput=”false” then the output can be viewed by running the application


and typing the following URL - https://localhost:44356/trace.axd and if it is true
the output will be displayed within the page.

* Build Solution - compiles code files (dll and exe) that have changed.
*Rebuild Solution - Deletes all compiled files and Compiles them again regardless of
whether or not the code has changed.
Windows Communication foundation - WCF is a technology, which unites .Net
Remoting, MSMQ, Web Services and COM+ technologies. It provides a common
platform for all .Net communication. It is the latest Service oriented technology.
Interoperability is the fundamental characteristics of WCF.
WCF provides a runtime environment for defining and exposing services, and to
consume other services as CLR types. WCF service can be hosted on IIS for
consumption.
WCF Scenarios - .Net Remoting works only within the network and not for internet
applications. If a software developed in Java wants to access some existing software
designed in .Net over internet and some other software wants to access this existing
software over intranet, within the Local area network, then this software can use WCF
services since WCF unites different technologies together. Here WCF service will
communicate with the Java based software on internet using HTTP protocol and
the .NET software using TCP.
Address: In WCF, every service is associated with a unique address. The address
provides two important elements: the location of the service and the protocol used to
communicate with the service.
WCF supports following transport methods -
1) HTTP
2) TCP
3) Peer Network
4) IPC(Inter Process communication)
5) MSMQ
Addresses have the following format:[base address]/ [optional URI]
Sample Addresses are:
http://localhost:8005
http://localhost:8005/firstservice
net.tcp://localhost:8002/sampleservice
net.pipe://localhost/piped
net.msmq://localhost/firstservice
Bindings: Specifies how a service is accessible. The method of communication
between the two parties is defined. (HTTP, TCP, NamedPipe, Peer2Peer and MSMQ),
encoding (text, binary etc.) and protocols (like transactional support or reliable
messaging).
Basic binding - Offered by the BasicHttpBinding class, this is designed to expose a
WCF service as a legacy ASMX web service, so that old clients can work with new
services. When used by the client, this binding enables new WCF clients to work with
old ASMX services.
Contracts: In WCF, all services expose contracts. The contract is a platform-
independent and standard way of describing what the service does. Here we can define
methods/actions. WCF defines four types of contracts.
Service contracts: Describe which operations the client can perform on the service.
Data contracts: Define which data types are used in the communication to and from the
service.
Fault contracts: Defines how the errors are raised and handled by the service and
passed on to the clients.
Message contracts: Allow the service to interact directly with messages
.NET Core - .NET Core is used to create server applications that run on Windows,
Linux and Mac. It does not currently support creating desktop applications with a user
interface. .NET Core Framework can be used to build different types of applications
such as mobile, desktop, web, cloud, IoT, machine learning, microservices, game, etc.
Net Core does not support desktop application development and it rather focuses on the
web, windows mobile, and windows store.
Kestrel is a cross-platform web server for ASP.NET Core. It is supported on all
platforms and operating systems that . NET Core supports. It is included by default as
internal server in ASP.NET Core.
The .NET Core command-line interface (CLI) is a new cross-platform tool for creating,
restoring packages, building, running and publishing .NET applications.
The following command creates a new console application named
MyConsoleSampleApp to MyApps directory. The -o or --output option is used to specify
an output directory where the project should be generated.
dotnet new console -n MyConsoleSampleApp -o C:\MyApps
Project structure -
1) csproj File - Right-click on the project and then click on Edit Project File to edit
the .csproj file. It defines the .Net framework version. On adding the dependencies
through NuGet, it will add another element which contains the details of the Package in
PackageReference element.
2) launchSettings.json - Properties folder contains a file i.e. launchSettings.json file
which contains all the information required to launch the application. It contains the
profiles through which the application can be run, each profile is mapped to a
commandName, applicationUrl on which application is launched, environmentVariables,
etc.
3) appsettings.json - same as web.config. It defines ConnectionStrings, Security etc.
4) Program.cs - This file contains the main method which is the entry point for the
application. It will create a web host builder and configure the services defined in
Startup.cs file. The host configures a server and a request processing pipeline. The host
can also set up logging, dependency injection, and configuration.
5) Startup.cs - This file used to define all services used in the application and configure
the HTTP Request pipeline with the use of middleware components Middleware are
software components that are assembled into an application pipeline to handle requests
and responses. E.g., Logger, Authorization and Routing.
6) wwwroot Folder - this folder stores static files like CSS, Javascript, images, icons,
etc.
The .NET Core Framework composed of the following parts:
CLI Tools: A set of tools for development and deployment. It is a command line
interface.
Roslyn: Language compiler for C# and Visual Basic
CoreFX: Set of framework libraries.
CoreCLR: A JIT based CLR (Command Language Runtime).
Working with .Net Core Libraries - Code reusability is a very useful feature of modern
programming languages. Software developers often share same functionality among
multiple applications to avoid the duplication of code and maintain code standards and
quality.
Let’s say, Developer X (DevX) creates a Matrix class that provides functionality to add,
multiply, subtract two matrices. Now, Developer Y (DevY) and Developer Z (DevZ) also
need same functionality. The first option is, either DevY and DevZ also write similar
code to implement same functionality, or they can use the same code that DevX has
written already. This can be achieved by creating Class Library containing the functions
for addition, multiplication and subtraction of two matrices.
Delegates and Events - Delegate is a type in C# and represents a reference to a
method. It is like a function pointer. Delegate has list of parameters and a return type.
The method which the delegate points to can be either static or non-static (instance).
“Action” and “Func” are delegate types provided by the .NET Framework (.NET Core).
There are two high-level types of delegates - A delegate that returns a type and a
delegate that returns nothing. “Func” can have 17 different possible forms.
For Example - Func<T, TResult>
We can replace delegate with Func, Func<int, int> -i .e., a Func with input as an Integer
and returns an output of Integer.
Events - Events trigger/invoke functions. The event keyword is used to declare an
event in C# (.NET Core). Unlike delegate, the event is treated as an instance member.
And that is a fundamental difference between event and delegate.
An event is always associated with the delegate. When an event is raised, the delegate
is called back, and the function attached to the delegate gets called.

.Net Core Security - Two important concepts -


Authentication - Defines the identity of the user, when a user logs on.
Authorization - Process of granting permissions on resources.
1) Select ASP .Net MVC (.NetCore) Project
2) To add identity right click on Controllers folder in solution explorer and select
Add=>New Scaffolded Items from the context menu.
3) select Identity under Installed and click on Add Button.
4) After adding Identity, you need to specify few things on the screen below -
Select the layout page from the project files
Select Login & Logout file to be overridden
Select Register file
Add new data context class
Add new User class using
5) Following packages will get installed -
Microsoft.VisualStudio.Web.CodeGeneration.Design
Microsoft.EntityFrameworkCore.Sqlsever
Microsoft.EntityFrameworkCore.Tools
Microsoft.AspNetCore.Identity.UI
Microsoft.AspNetCore.Identity.EntityFrameworkCore
6) Following code is generated -
Areas/Identity/IdentityHostingStartup.cs file - This works like a starting class for the
project. This class holds the configuration of identity-related services & Entity framework
configuration for identity.
Areas/Identity/SampleAppUser.cs - This file is derived from Identity User. This class
allows you to add your own fields for user profiles.
Area/Identity/SampleAppContext.cs - This file is the entity framework context class
used by Identity. It defines the database for the identity.
Also SQL Server connection is added to Appsettings.json file.
7) To automate the migrations & create a database for Identity we need to run the
following commands in the package manager console (Tools-NuGet Manager-Package
Manager Console)
add-migration InitialMigration
update-database
This also updates the database with our user defined fields.
8) For Identity-related links Login, Logout & Register to appear to add following code to
application layout file i.e Views/Shared/_Layout.cshtml. Add it in the header tag. It is
shared file.
<div class="col-md-2">
<partial name="_LoginPartial.cshtml" />
</div>
9) Make changes to Startup class to add Authentication, Razor Pages & Endpoints for
Razor Pages
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddRazorPages();
}
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
10) Also, note that only users with confirmed email are allowed to log in so after
registering a user link to confirm the email is available which should be clicked to
confirm email.
11) Add a property in User class
public class SecurityMVCCookiesUser: IdentityUser
{
public string surname { get; set; }
}
12) add an input box to Areas/Identity/Pages/Account/Register.cshtml for user to enter
"surname" as part of the registration process. We will below HTML in Register.cshtml
before Email Input
<div class="form-group">
<label asp-for="Input.surname"></label>
<input asp-for="Input.surname" class="form-control" />
<span asp-validation-for="Input.surname" class="text-danger"></span>
</div>
13) Then we need to add FullName property in InputModel class in Register.cshtml.cs
public class InputModel
{
[Required]
[RegularExpression(@"^[a-zA-Z]+$", ErrorMessage ="The name cannot contain
nos.")]
[Display (Name = "surName")]
public string surname {get; set; }
}
12) Finally, we need set the value for FullName property in OnPostAsync method
in Register.cshtml.cs file, to save that to the database in AspNetUsers table in
column surname.
var user = new SecurityMVCCookiesUser{ UserName = Input.Email, Email =
Input.Email, surname = Input.surname };

Multithreading in C# - A thread is defined as the execution path of a program. If your


program involves complex and time consuming operations, then it is often helpful to set
different execution paths or threads, with each thread performing a different task.
Threads are lightweight processes. One common example of use of thread is
implementation of concurrent programming by modern operating systems. Example, In
MS Word application, we get spelling mistakes while typing in the document, so both
input and spell check is happening simultaneously in the same program.
Thread Life Cycle - The life cycle of a thread starts when an object of the
System.Threading.Thread class is created and ends when the thread is terminated or
completes execution.
Following are the various states in the life cycle of a thread −
1) The Unstarted State − It is the situation when the instance of the thread is created
but the Start method is not called.
2) The Ready State − It is the situation when the thread is ready to run and waiting CPU
cycle.
3) The Not Runnable State − A thread is not executable, when
Sleep method has been called
Wait method has been called
Blocked by I/O operations
4) The Dead State − It is the situation when the thread completes execution or is
aborted.
Deploying .Net Core Web Application -
From Tools -Command Line -
execute the following command -
dotnet publish
dotnet publish -r linux-x64 --self-contained false
This creates an executable and .dll file.
Publishing your app as self-contained produces a platform-specific executable. The
publish folder contains all components of the app, including the .NET libraries and target
runtime. The app is isolated from other .NET apps and doesn't use a locally installed
shared runtime. The user of your app isn't required to download and install .NET.
Copy the complete published folder to the Client's machine and run the executable file
and then Open the app inside the browser at port 5001 and run the application

You might also like