Академический Документы
Профессиональный Документы
Культура Документы
Lecture 01
Fayyaz Muhammad
Assistant Professor
Lecture 01
Course Introduction
Reference Book(s)
ASP.Net Core in Action, Andrew Lock, 1st Edition 2018, Manning
Microsoft Visual C# Step by Step, John Sharp, 9th Edition, 2018, Pearson
Education, Inc.
WEB TECHNOLOGIES, A Computer Science Perspective, Jeffrey C. Jackson, 2007,
Pearson Education, Inc.
Note: Above ASP.Net Books cover the open-source version of ASP.NET that runs on
Windows, Linux, macOS, and Docker
Online Resources
Wikipedia: https://en.wikipedia.org/wiki/World_Wide_Web
Tektutorialshub: https://www.tektutorialshub.com/asp-net-core-tutorial/
Tutorials Point:
https://www.tutorialspoint.com/internet_technologies/websites_development.htm
Classroom Requirements
Windows 10 (Current Version)
Lectures
Demonstration and Hands on exercises
Class Discussion
Learning Objectives
Web Development
Web Application
A client-server application program (collection of files and
program), stored on a remote server that uses web
browsers and web technology to perform specific function
over the Internet through a browser interface for web
users.
Examples of Web Applications
Few of the examples of Web Applications are:
Online Banking
Social Networking
Online Reservations
Online Forums
Next, the Web server sends the user request to the appropriate web application server.
The server performs a specified function such as querying the database or processing
the requested data
The server forwards the user data to the web server with the requested information.
In the end, the Web server displays the requested information of a user on the browser
How web application works…?
Web Apps & Other Apps
Google docs is also a word-processing app but user can perform all the
functions using a web browser without installing it, that is a web app.
Mobile App vs Web App
A mobile application (mobile app or simply an app)
a computer program or software application designed to run on a mobile
device such as a phone, tablet, or watch.
Desktop Apps and Mobile Apps
which are designed to run on desktop computers, and mobile
devices
Web applications which run in mobile web browsers rather than
directly on the mobile device.
Web Site Vs Web App
A website (also written as web site)
is a collection of web pages and related content that is identified by a
common domain name and published on at least one web server.
Some examples
wikipedia.org
google.com
amazon.com.
All publicly accessible websites collectively constitute the World
Wide Web.
Private websites
that can only be accessed on a private network, such as a company's internal
website for its employees.
Website VS Web App
Websites are generally meant to provide information
Websites provide no or minimal interaction
are meant for computers to read as Web App is meant for humans to read
Web Development
Thank You
ITEC 4116
Advance Web Application Development
Lecture 02
Fayyaz Muhammad
Assistant Professor
Lecture 02
Learning Objectives
Working of Web Based Systems
How world wide web works
Understand Web Technologies
Summary of last lecture
Software Application extends to Web Application
Web Development
Mechanics of Web
How Web Works?
To understand why the Web supplanted the other technologies, it will be
helpful to know a bit about the mechanics of the Web and other Internet
information management technologies.
All of these technologies consist of (at least) two types of software:
server and client
An Internet-connected computer that wishes to provide information to
other Internet systems must run server software, and a system that wishes
to access the information provided by servers must run client software (for
the Web, the client software is normally a web browser). The server and
client applications communicate over the Internet using TCP/IP protocol.
The protocol used by the Web is the Hypertext Transport Protocol,
Elements of Web Based System
The fundamental elements or principal components of a Web
system are:
A Web server
A Network
A Client browsers
Web applications can be simple consisting of only static web pages or they
can be dynamic and interactive.
Web applications also include:
An application server
Enables the system to manage business logic and state
A Database Server
Which provides the data for the application
The Internet
The Internet is the global system of interconnected computer networks that
uses the Internet protocol suite (TCP/IP) to link devices worldwide.
It is a network of networks that consists of private, public, academic, business,
and government networks of local to global scope, linked by a broad array of
electronic, wireless, and optical networking technologies.
The resources of the WWW are transferred via the Hypertext Transfer
Protocol (HTTP) and may be accessed by users by a software
application called a web browser and are published by a software application
called a web server.
Internet VS WWW
WWW can be defined in much the same way as the Internet
While the Internet can be thought of as the collection of machines that are
globally connected via IP, the World Wide Web can be informally defined as the
collection of machines (web servers) on the Internet that provide information via
HTTP, and particularly those that provide HTML documents.
Information system
Web resources
Hypertext
Web Browser
Web Server
Information system
Information systems (IS) are formal, sociotechnical,
organizational systems designed to collect, process, store,
and distribute information. In a sociotechnical perspective,
information systems are composed by four components:
task, people, structure, and technology.
Hypertext Transfer Protocol (HTTP)
HTTP is universally agreed-upon foundational protocol for format of transmitting
data over a network for distributed, collaborative, hypermedia information
systems how web clients and servers should communicate.
Primary or most-commonly-used HTTP verbs (or methods, as they are properly called)
are:
These correspond to create, read, update, and delete (or CRUD) operations, respectively.
GET—to requests a representation of the specified resource. Requests using GET should
only retrieve data. It is the primary and default method whenever you click a link
POST — to submit an entity to the specified resource, often causing a change in state or
side effects on the server.
HTTP Methods/Request Methods …
PUT—to replaces all current representations of the target resource with the
request payload.
The second part gives the server Internet address (e.g., www.UE-
hardware.com).
The rest names a resource on the web server (e.g., /specials/SOS.pdf).
According to the RFC, the URL combines a name and an access
method.
Every URL is a URI. All URLs are URIs, but not all URIs are URLs.
A URI is an identifier. The URL is the location.
Uniform Resource Name (URN)
The second flavor of URI is the uniform resource name, or URN.
urn:ietf:rfc:2141
2. If the server is specified using a host name (rather than an IP address), use DNS to
convert this name to the appropriate IP address.
3. Establish a TCP connection using the IP address of the specified web server.
4. Send the HTTP request over the TCP connection and wait for the server’s
response.
5. Display the document contained in the response. If the document is not a plain-
text document but instead is written in a language such as HTML, this involves
rendering the document: positioning text and graphics appropriately within the
browser window, creating table borders, using appropriate fonts and colors, etc.
Before discussing various features of browsers that can be controlled by us
Web servers
The primary feature of every web server is to accept HTTP requests from
web clients and return an appropriate resource (if available) in the HTTP
response. Even this basic functionality involves a number of steps:
1. The server calls on TCP software and waits for connection requests to
one or more ports.
4. The subtask examines the Host header field of the request to determine
which “virtual host” should receive this request and invokes software for
this host.
Web servers
1. The virtual host software maps the Request-URI field of the HTTP request start
line to a resource on the server.
2. If the resource is a file, the host software determines the MIME type of the file
(usually by a mapping from the file-name extension portion of the Request-URI),
and creates an HTTP response that contains the file in the body of the response
message.
3. If the resource is a program, the host software runs the program, providing it
with information from the request and returning the output from the program
as the body of an HTTP response message.
4. The server normally logs information about the request and response—such as
the IP address of the requester and the status code of the response—in a plain-
text file.
5. If the TCP connection is kept alive, the server subtask continues to monitor the
connection until a certain length of time has elapsed, the client sends another
request, or the client initiates a connection close.
Web Technology
Web technology is the development of mechanism that allows two or more
computer devices to communicate over a network
The development of web-based applications requires knowledge about the
underlying technology and the formats and standards the web is based
upon.
Browsers Web Servers
Programming Languages Database Systems
HTML CSS
JavaScript Libraries (JQuery, etc.)
Web Development Frameworks Protocols like HTTP
APIs Data Format (xml, json & csv)
Summary
Working of Web Based Systems
How world wide web works
Understand Web Technologies
Thank You
ITEC 4116
Advance Web Application Development
Lecture 03
Fayyaz Muhammad
Assistant Professor
Lecture 03
Learning Objectives
Introduction to Web Framework
Choosing a Web Framework
Microsoft Web Technologies
Overview of ASP.NET
Introduction to ASP.NET Core MVC
Summary of last lecture
Working of Web Based Systems
Overview of Microsoft Web Technologies
How world wide web works
Understand Web Technologies
Web Framework
A web framework (WF) or web application framework (WAF) is a software
framework that is designed to support the development of web
applications including web services, web resources, and web APIs. Web
frameworks provide a standard way to build and deploy web applications
on the Web
For example, many web frameworks provide libraries for database access,
templating frameworks, and session management, and they often
promote code reuse.
For instance, the website in which you are reading this blog. Everything that you
see right now from the text, images, spacing, and that small notification button
in the bottom right corner; everything comes in the front end.
A combination of CSS, HTML, and JavaScript is used for writing the client-side
code. This code is parsed by the web browser. Unlike the server-side code,
client-side code can be seen as well as modified by the user. It reacts to user
input.
The client-side code communicates only via HTTP requests and is not able to
read files off a server directly.
Server Side Development
Any code that is able to respond to HTTP requests has the ability
to run on a server. The server-side code is responsible for
creating the page that the user requested as well as storing
different types of data, including user profiles and user input. It
is never seen by the end-user.
For sever side development you need programming language.
Some of the Top Programming Languages that You Can Choose
from are:
PHP
Python
Java
Ruby
C#
Server Side Frameworks
The frameworks are tools that help developers code the backend
in a specific programming language. Different frameworks are
used for different languages and development needs. Some of the
top backend frameworks that you can choose from are
Server Side Database
The storage unit for all the data of your website is a database.
Some of the top backend Databases that you can choose from
are:
MySQL
SQLite 3
Casandra
MongoDB
Postgre SQL
Elasticsearch
Microsoft technology stack
Primarily includes:
The .NET Framework – the basis for all of our development.
C#--as the preferred programming language, but we are capable of meeting our client’s
needs for any of the .NET languages.
ASP.NET MVC and HTML5 --preferred for rapid web application development.
Window Presentation Foundation (WPF) -- preferred technology for Windows-based smart
client applications.
Windows Communication Foundation (WCF) -- to implement tiered service-oriented
applications.
SQL Server – Database Technology for business application
SQL Server Reporting Services – for business application
SharePoint is the collaboration tool -- for enterprise integration.
Microsoft Azure – platform for hosting database in the cloud, serverless relational
databases such as Azure SQL and Non-relational databases such as NoSQL
Introduction to ASP.NET Core MVC
ASP.NET Core MVC is a radical shift for web developers using the
Microsoft platform. It emphasizes clean architecture, design
patterns, and testability, and it doesn’t try to conceal how the Web
works.
ASP.NET Core MVC is a web application development framework
from Microsoft that combines the effectiveness and tidiness of
model-view-controller (MVC) architecture, ideas and techniques
from agile development, and the best parts of the .NET platform.
Understanding the History of ASP.NET Core MVC
Original ASP.NET was introduced in 2002
When Microsoft was keen to protect a dominant position in traditional
desktop application development and saw the Internet as a threat.
Below figure illustrates Microsoft’s technology stack as it appeared then.
ASP.NET Web Forms
Idea was to make web development feel just the same as developing a
desktop application.
In With Web Forms, Microsoft attempted to hide both HTTP, with its intrinsic
statelessness, and HTML which at the time was unfamiliar to many
developers, by modeling the user interface (UI) as a hierarchy of server-side
control objects.
Each control kept track of its own state across requests, rendering itself as
HTML when needed and automatically connecting client-side events (for
example, a button click) with the corresponding server-side event handler
code. In effect, Web Forms is a giant abstraction layer designed to deliver a
classic event-driven graphical user interface (GUI) over the Web.
Developers could think in terms of a stateful UI and didn’t need to work with
a series of independent HTTP requests and responses.
Microsoft could seamlessly transition the army of Windows desktop
developers into the new world of web applications.
What Was Wrong with ASP.NET Web Forms?
ASP.NET Web forms were good in development but proved more complicated:
View State weight: The actual mechanism for maintaining state across requests (known as
View State) resulted in large blocks of data being transferred between the client and server.
This data could reach hundreds of kilobytes in even modest web applications, and it went
back and forth with every request, leading to slower response times and increasing the
bandwidth demands of the server.
Page life cycle: The mechanism for connecting client-side events with server-side event
handler code, part of the page life cycle, could be complicated and delicate.
Few developers had success manipulating the control hierarchy at runtime without creating
View State errors or finding that some event handlers mysteriously failed to execute.
False sense of separation of concerns: ASP.NET Web Forms’ code-behind model provided a
means to take application code out of its HTML markup and into a separate code-behind class.
This was done to separate logic and presentation, but, in reality, developers were encouraged
to mix presentation code (for example, manipulating the server-side control tree) with their
application logic (for example, manipulating database data) in these same monstrous code-
behind classes. The end result could be fragile and unintelligible. Traditional ASP.NET Web
Forms development was good in principle, but reality proved more complicated.
What Was Wrong with ASP.NET Web Forms?
Limited control over HTML: Server controls rendered themselves as HTML, but not
necessarily the HTML you wanted. In early versions of ASP.NET, the HTML output failed
to meet web standards or make good use of Cascading Style Sheets (CSS), and server
controls generated unpredictable and complex ID attributes that were hard to access
using JavaScript.
These problems have improved in recent Web Forms releases, but it can still be tricky
to get the HTML you expect.
Leaky abstraction: Web Forms tried to hide HTML and HTTP wherever possible.
As you tried to implement custom behaviors, you frequently fell out of the abstraction,
which forced you to reverse-engineer the postback event mechanism or perform
obtuse acts to make it generate the desired HTML.
Low testability: The designers of Web Forms could not have anticipated that
automated testing would become an essential component of software development.
The tightly coupled architecture they designed was unsuitable for unit testing.
Integration testing could be a challenge, too.
What Was Wrong with the Original MVC Framework?
At the time the MVC Framework was created, it made sense for Microsoft to create it on
top of the existing ASP.NET platform, which had a lot of solid low-level functionality that
provided a head start in the development process and which was already well-known
and understood by ASP.NET developers.
But compromises were required to graft the MVC Framework onto a platform that was
originally designed for Web Forms.
MVC Framework developers became used to using configuration settings and code
tweaks that disabled or reconfigured features that didn’t have any bearing on their web
application but were required to get everything working.
As the MVC Framework grew in popularity, Microsoft started to take some of the core
features and add them to Web Forms.
The result was increasingly odd, where features with design quirks required to support
the MVC Framework were extended to support Web Forms, with further design quirks to
make everything fit together.
At the same time, Microsoft started to expand ASP.NET with new frameworks for creating
web services (Web API) and real-time communication (SignalR).
The new frameworks added their own configuration and development conventions, each
of which had its own benefits and oddities, and the overall result was a fragmented
mess.
The Original MVC Framework
In October 2007, Microsoft announced a new development platform, built on the existing
ASP.NET platform, that was intended as a direct response to the criticisms of Web Forms
and the popularity of competing platforms such as Ruby on Rails.
The new platform was called the ASP.NET MVC Framework and reflected the emerging
trends in web application development, such as HTML and CSS standardization, RESTful
web services, effective unit testing, and the idea that developers should embrace the
stateless nature of HTTP.
The concepts that underpin the original MVC Framework seem natural and obvious now,
but they were lacking from the world of .NET web development in 2007.
The introduction of the ASP.NET MVC Framework brought Microsoft’s web development
platform back into the modern age.
The MVC Framework also signaled an important change in attitude from Microsoft, which
had
previously tried to control every component in the web application toolchain.
With the MVC Framework, Microsoft built on open source tools such as jQuery, took on
design conventions and best practices from competing (and more successful) platforms,
and released the source code to the MVC Framework for developers to inspect.
What is a .NET?
.NET has been a great technology for creating applications on the Windows platform.
Now .NET is a great technology for creating applications on Windows, Linux, and the
Mac.
Now .NET code is open-source code, you can create apps for other platforms, and
.NET uses modern patterns.
.NET Core and NuGet packages allow Microsoft to provide faster update cycles for
delivering new features.
Choosing your Technologies
Choosing to learn and develop with a new framework is a big investment
It’s not easy to decide what technology should be used for creating
applications. different technologies available for creating Windows and
web apps and services
But why choose ASP.NET Core?
Using a Web Framework
Just as you may have used desktop or mobile development frameworks for
building native applications, ASP.NET Core makes writing web applications
faster, easier, and more secure. It contains libraries for common things like
Letting users use their Facebook account to log in to your web app using
OAuth
Lecture 04
Fayyaz Muhammad
Assistant Professor
Lecture 04
Learning Objectives
Introduction to .NET
Working of .NET
.NET Features
.NET Components
Common Language Runtime (CLR)
Components of CLR
Class Library
Summary of last lecture
Web Frameworks and Microsoft Framework
How it has evolved from Web Forms and the original ASP.NET
MVC Framework.
Purpose
To overcome the shortcoming of previous programming technologies
With .NET, you can use multiple languages, editors, and libraries to build
for web, mobile, desktop, gaming, and IoT.
Cross Platform
.NET Framework
Xamarin/Mono
Libraries
To convert the Managed Code into native code and then execute the Program.
When .NET application is executed at that time control will go to OS, then OS Create
a process to load CLR
The program used by the operating system for loading CLR is called runtime host,
which are different depending upon the type of application that is desktop or web
based application i.e.
Reference Types
Garbage Collector
Provide the Automatic Memory Management feature
Lecture 05
Fayyaz Muhammad
Assistant Professor
Lecture 05
Learning Objectives
Program, Programming and Programming Language
Programming Language Basic Elements
.NET Framework and C# Programming Language
Working of .NET With C# Programming Language
C# Program Working Example
Summary of Last Lecture
Introduction to .NET
Working of .NET
.NET Features
.NET Components
Common Language Runtime (CLR)
Components of CLR
Class Library
Online Resources
Wikipedia: https://en.wikipedia.org/wiki/
IEEE: https://spectrum.ieee.org/computing/software/the-top-programming-
languages-2019
Lecture 06
Fayyaz Muhammad
Assistant Professor
C# Program Structure
C# Program Components
Tutlane: https://www.tutlane.com/tutorial/csharp/csharp-introduction
Organizational Concepts in C# Language
The key organizational concepts in C# are:
Programs
Namespaces
Types
Members
Assemblies
C# Program (Our First Program)
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
/* hello program in C# */
Console.WriteLine("Hello World!");
}
}
}
C# Program Syntax and Semantics
Program—consists of instructions to solve a problem. These instructions are
also called actions that a program takes
Expressions
Statements
Arrays
Interfaces
Delegates
Attributes
C# Program (Starting Point)
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
/* hello program in C# */
Console.WriteLine("Hello World!");
}
}
}
Basic Structure
of C# Program
Parts of a C# Program
A C# program consists of the following parts −
Namespace declaration
A Class
Class methods
Class attributes
A Main method
C# Program Structure
C# Program Components
Lecture 07
Fayyaz Muhammad
Assistant Professor
C# Program Structure
C# Program Components
Wikipedia: https://en.wikipedia.org/wiki/
Tutlane: https://www.tutlane.com/tutorial/csharp/csharp-introduction
Organizational Concepts in C# Language
The key organizational concepts in C# are:
Programs
Namespaces
Types
Members
Assemblies
Elements of the C# Language
Following topics provide an overview of the elements of the C# language:
Program Structure
Expressions
Statements
Arrays
Interfaces
Delegates
Attributes
Character Set
C# programs are written using the Unicode character set
Case Sensitivity
Statement Termination
Block
Whitespace
Comments
Case Sensitivity
C# is Case Sensitive Language
The word “Main” is not the same as:
Why Comments?
Comments are for humans to read and not for computers
Types of Comments
Multi-Line Comments
C# Multi-line Comments
Start with /* and ends with */
C# Comments Examples
C# Whitespace
C# is a “free format” language
Why Whitespaces?
used by the programmer to make the code clearer and easier to read
C# Whitespace Examples
C# Blocks
C# is a block structured language
Block
Any statements within and including “{” and “}” define a block
Why Blocks?
Blocks define the scope or life time of a program
To repeat statements
Lecture 08
Fayyaz Muhammad
Assistant Professor
Wikipedia: https://en.wikipedia.org/wiki/
Tutlane: https://www.tutlane.com/tutorial/csharp/csharp-introduction
Organizational Concepts in C# Language
The key organizational concepts in C# are:
Programs
Namespaces
Types
Members
Assemblies
Elements of the C# Language
Following topics provide an overview of the elements of the C# language:
Program Structure
Expressions
Statements
Arrays
Interfaces
Delegates
Attributes
Lowest Level of Syntax and Structure
Lexical Structure
is the structure of the words of the programming language
lexical structure of a language determines what constitutes the words that are in the
language
Tokens
Words of the programming language are called tokens
Types of Tokens
Keyword
Identifier
Operator
Punctuator
Literal
C# Working Example
C# Tokens
C# Keywords (Reserved Words)
A keyword is a reserved word in the C# language
Keywords are predefined sets of reserved words that have special meaning in a
program
C# includes various categories of keywords e.g.:
access keywords (base, this)
access modifiers keywords (public, private, protected, internal)
statement keywords (if, for, while, switch, case, do, foreach, in, break, continue, goto etc.)
method param keywords (params, ref, out)
Type Keywords (bool, int, float, char, string, double, decimal, long, date, short, uint,
ushort, class, struct etc.)
Literal Keywords (null, false, true, value, void)
Operator Keywords (as, is, sizeOf, new, typeOf)
C# Keywords
C# has a total of 79 keywords. All these keywords are in lowercase.
C# Keywords (Reserved Words) …
Although keywords are reserved words, they can be used as identifiers if
@ is added as prefix.
For example,
int @void;
Names can contain letters, digits and the underscore character (_)
Names should start with a lowercase letter and it cannot contain whitespace or
symbol such as? - + ! @ # % ^ & * ( ) [ ] { } . ; : " ' / and \
Names are case sensitive ("myVar" and "myvar" are different variables)
Reserved words (like C# keywords, such as int or double) cannot be used as names
Summary
Lowest Level Syntactic Elements and Structure of C#
Programming Language (Lexical Structure)
Tokens
Types of Tokens
Keywords
Identifiers`
Thank You
ITEC 4116
Advance Web Application Development
Lecture 09
Fayyaz Muhammad
Assistant Professor
Wikipedia: https://en.wikipedia.org/wiki/
Tutlane: https://www.tutlane.com/tutorial/csharp/csharp-introduction
C# Operators
Operators are symbols that are used to perform operations on
operands
Operands may be variables and/or constants.
Types of Operators
Assignment Operators—(=)
Arithmetic Operators—(+, -, *, /, %)
Lecture 10
Fayyaz Muhammad
Assistant Professor
Wikipedia: https://en.wikipedia.org/wiki/
tutlane: https://www.tutlane.com/tutorial/csharp/csharp-introduction
int billAmount=25000;
To declare more than one variable of the same type, use a comma-
separated list:
int x = 5, y = 6, z = 50;
Constants
Constants—Data values that stay the same every time a program
is executed are known as constants. A data item whose value cannot change
during the program’s execution
Variable—A data item whose value can change during the program’s
execution
Programs
Namespaces
Types
Members
Assemblies
Elements of the C# Language
Following topics provide an overview of the elements of the C# language:
Program Structure
Expressions
Statements
Arrays
Interfaces
Delegates
Attributes
Summary
Program, Data and Type
Data Types
Variables
Variable Creation (Declaration)
Constants—Variables VS Constants
Types of C# Data Types
C# Program Example for Variable Declaration
Thank You
ITEC 4116
Advance Web Application Development
Lecture 11
Fayyaz Muhammad
Assistant Professor
Namespace
Creating Namespace
Namespace members
Using Keyword
Data Types
Variables
Constants—Variables VS Constants
tutlane: https://www.tutlane.com/tutorial/csharp/csharp-introduction
To organize code
namespace Namespace-Name
{
//Body of namespace
}
Using a Namespace in C#
A namespace can be included in a program using the using keyword
The syntax is:
using Namespace-Name;
Console.WriteLine("Hello World!");
System.Console.WriteLine("Hello World!");
Namespace Members
A namespace can have following types as its members:
Classes
Interfaces
Structures
Delegates
Programs
Namespaces
Types
Members
Assemblies
Elements of the C# Language
Following topics provide an overview of the elements of the C# language:
Program Structure
Expressions
Statements
Arrays
Interfaces
Delegates
Attributes
Summary
C# Program Example of Using Variables
Namespace
Creating Namespace
Namespace members
Using Keyword
Lecture 12
Fayyaz Muhammad
Assistant Professor
Expressions
Types of Expressions
Types of Statements
Declaration Statements
Expression Statements
Namespace
Creating Namespace
Namespace members
Using Keyword
Wikipedia: https://en.wikipedia.org/wiki/
tutlane: https://www.tutlane.com/tutorial/csharp/csharp-introduction
Organizational Concepts in C# Language
The key organizational concepts in C# are:
Programs
Namespaces
Types
Members
Assemblies
Elements of the C# Language
Following topics provide an overview of the elements of the C# language:
Program Structure
Expressions
Statements
Arrays
Interfaces
Delegates
Attributes
Program and Statement
Program—is a set of instruction that perform some task
System.Convert.ToInt32("35");
Why Expression
Expressions Types
Expressions can consist of a literal value, a method invocation, an
operator and its operands, or a simple name.
Based on the above, Expressions have following types:
Literal Value
A literal is a constant
value that has no name. For example, in the
following code example, both 5 and "Hello World" are literal values:
int i = 5;
Simple Name
DoWork( );
Expressions are often classified by the type of value that they represent.
For example:
Assigning values
Calling methods
Declaration Statements
Expression Statements
Expressions
Types of Expressions
Types of Statements
Declaration Statements
Expression Statements
Lecture 13
Fayyaz Muhammad
Assistant Professor
Boolean Expressions
Switch Statement
Assemblies
Summary of Last Lecture
Program and Statement
Expressions
Types of Expressions
Types of Statements
Declaration Statements
Expression Statements
Tutlane: https://www.tutlane.com/tutorial/csharp/csharp-introduction
Edureka!: https://www.edureka.co/blog/c-sharp-tutorial/#condition
Organizational Concepts in C# Language
The key organizational concepts in C# are:
Programs
Namespaces
Types
Members
Assemblies
Elements of the C# Language
Following topics provide an overview of the elements of the C# language:
Program Structure
Expressions
Statements
Arrays
Interfaces
Delegates
Attributes
Flow Control Statements
C# Provides following statements used to control the flow of execution in
a program:
Selection statements
If, else, switch, case
Iteration statements
do, for, foreach, in, while
Jump statements
break, continue, default, goto, return, yield
// if-else statement
if (condition)
{
then-statement;
}
else
{
else-statement;
}
// Next statement in the program.
If Statements (Examples)
bool condition = true;
if (condition)
{
Console.WriteLine("The variable is set to true.");
}
Each switch section contains one or more case labels (either a case or default
label) followed by one or more statements.
The advantage of using switch over if...else if statement is the code will look
much cleaner and readable with switch.
The default case
The switch statement may include at most one default label placed in any
switch section.
The default case specifies the switch section to execute if the match
expression doesn't match any other case label.
If a default case is not present and the match expression doesn't match any
other case label, program flow falls through the switch statement.
The default case can appear in any order in the switch statement.
Regardless of its order in the source code, it's always evaluated last, after all
case labels have been evaluated.
Switch Statement
Switch Statement Syntax
switch (expression) 1.The switch statement tests the
{ variable against a set of
case <value1>
constants.
// code block
break; 2.The switch statement contains
case <value2> multiple case labels.
// code block 3.The switch case must include
break;
'break' keyword to stop the
case <valueN>
// code block execution of switch case.
break; 4.The default case executes when
default no case satisfies the expression.
// code block
5.A nested switch statement is
break;
} allowed.
using System;
Switch Example public class Example
{
public static void Main( )
{
int caseSwitch = 1;
switch (caseSwitch)
{
case 1:
Console.WriteLine("Case 1");
break;
case 2:
Console.WriteLine("Case 2");
break;
default:
Console.WriteLine("Default case");
break;
}
}
} // The example displays the following output: // Case 1
Assemblies
An assembly is the primary building block of a .NET Framework application
The generated file can be either an executable files (.exe) or Dynamic Link
Library (.dll)
Boolean Expressions
Switch Statement
Assemblies
Thank You
ITEC 4116
Advance Web Application Development
Lecture 14
Fayyaz Muhammad
Assistant Professor
Iteration statements
for statement
while statement
do—while statement
foreach—in statement
Summary of Last Lecture
Flow Control Statements
Boolean Expressions
Switch statement
Assemblies
Online Resources
Wikipedia: https://en.wikipedia.org/wiki/
Tutlane: https://www.tutlane.com/tutorial/csharp/csharp-introduction
Edureka!: https://www.edureka.co/blog/c-sharp-tutorial/#condition
Flow Control Statements
C# Provides following statements used to control the flow of execution in
a program:
Selection statements
If, else, switch, case
Iteration statements
do, for, foreach, in, while
Jump statements
break, continue, default, goto, return, yield
while statement
do—while statement
foreach statement
for Loop
The for statement executes a statement or a block of
statements while a specified Boolean expression
evaluates to true.
while( condition )
{
statement(s);
}
It cannot be used to add or remove the items from the source (an array or
an object collection) (for loop does that).
All the statements continue to execute for the each element of an object or
an array. After that, the control is transferred to the next statement
following the foreach block
Iteration statements
for statement
while statement
do—while statement
foreach—in statement
Thank You
ITEC 4116
Advance Web Application Development
Lecture 15
Fayyaz Muhammad
Assistant Professor
Objects
Members
Access Modifiers
Arrays
Collections
Summary of Last Lecture
Flow Control Statements
Iteration statements
for statement
while statement
do—while statement
foreach—in statement
Online Resources
Wikipedia: https://en.wikipedia.org/wiki/
Tutlane: https://www.tutlane.com/tutorial/csharp/csharp-introduction
GeeksForGeeks: https://www.geeksforgeeks.org/c-sharp-class-and-object/
Programs
Namespaces
Types
Members
Assemblies
Elements of the C# Language
Following topics provide an overview of the elements of the C# language:
Program Structure
Expressions
Statements
Arrays
Interfaces
Delegates
Attributes
C# Class
Class—basic building block of object-oriented programming
Fields—variables that provide the state of the class and its objects
Methods—are used to implement the behavior of the class and its objects
Class Declaration
A class declaration contains only keyword class, followed by an
identifier (name) of the class as shown in the following example:
//[access modifier] - [class] - [identifier]
public class Customer
{
// Fields, properties, methods and events go here...
}
Source: https://www.tutlane.com/tutorial/csharp/csharp-classes-and-objects-with-examples
Objects
A class definition is like a blueprint that specifies what the type can do
(data and functionality)
The dot operator links the name of an object with the name of a
member
The dot operator is used both to access a method (and data) in class
just like Console.WriteLine( )
System.Console.WriteLine( )
C# - Arrays
A variable can hold only one literal value e.g. int x = 100;
store object
update object
delete object
retrieve object
sort object
Objects
Members
Access Modifiers
Arrays
Collections
Thank You
ITEC 4116
Advance Web Application Development
Lecture 16
Fayyaz Muhammad
Assistant Professor
Members
Access Modifiers
Arrays
Collections
Online Resources
Wikipedia: https://en.wikipedia.org/wiki/
DotNetTricks: https://www.dotnettricks.com/learn/aspnetcore
CodeMaze: https://code-maze.com/getting-started-with-asp-net-core-mvc/
Characteristics of Modern Web Applications
Expected Characteristics of Modern web applications:
Have higher user expectations and greater demands than ever before
the simplest being the host one or more rich SPA-like sub-applications
within a larger traditional web application
When to use Traditional Web Applications?
In Traditional Web Application development style, every time a user clicks, the
web request is sent back to the server and in response, the entire page is
reloaded. Even with AJAX calls to load only necessary component, the logic
against any action is done at the server level and then necessary UI or
component on the screen will load.
Application must already expose an API for other (internal or public) clients
Lecture 17
Fayyaz Muhammad
Assistant Professor
DotNetTricks: https://www.dotnettricks.com/learn/aspnetcore
CodeMaze: https://code-maze.com/getting-started-with-asp-net-core-mvc/
TEKTUTORIALHUB: https://www.tektutorialshub.com/asp-net-core/asp-net-core-building-first-
app/
ASP.NET Core Applications
Following Types of applications that can be developed and easily
deployed on any cloud, on-premises platform by using ASP.NET Core
Framework :
Web Applications
Web Services
Internet of Things (IoT) applications
Mobile backend services
The Framework:
Various ready to use project (application) and Item templates for fastest
development cycle
Easily integrate various client-side frameworks and libraries like
Angular, React, Bootstrap and many more
ASP.NET Core MVC Web App Creation using VS2019
Prerequisites
Visual Studio 2019 [Free Community Edition]
Main IDE to Write, compile, debug and optimize C# programs
NET Core 3.0 (SDK, Runtime)
Steps to create the project in Visual Studio 2019
Open Visual Studio 2019
Select “Create a New Project” from the “Get Started” list on the “Startup Page“
Select “ASP.NET Core Web Application” from the template list and click the Next
button
Give a “Project Name” and let the options as default
Select the “Web Application (Model-View-Controller)” template and click the Create
button
Select Solution Explorer and expand the project tree
Project Types
VS 2019 provides following types of the Project:
Console
Desktop
Web
Mobile
IoT
Game
Library
ETC
Solution
Whenever an app is created in VS2019, a project is created along with
a solution
Cannot be nested
Types
Empty
API
Web Application
Code Files
XML Files
HTML Pages
Style Sheets
ASP.NET Core Application Creation Demo
Summary
ASP.NET Core Applications
Steps to Create ASP.NET Web Application
Project Types
Project and Solution
Templates
Project Templates
Item Templates
ASP.NET Core MVC Application Creation Demo
Thank You
ITEC 4116
Advance Web Application Development
Lecture 18
Fayyaz Muhammad
Assistant Professor
Project Types
Templates
Project Templates
Item Templates
DotNetTricks: https://www.dotnettricks.com/learn/aspnetcore
CodeMaze: https://code-maze.com/getting-started-with-asp-net-core-mvc/
TEKTUTORIALHUB: https://www.tektutorialshub.com/asp-net-core/asp-net-core-building-first-
app/
Overview of an ASP.NET Core application
Source:
ASP.NET Core in Action
By Andrew Lock, 2018 Manning Publications Co
Web App MVC Project Structure
Web App MVC Project Structure
Project Structure of ASP.NET Core MVC
Project Files and Folders
Following are the items in a single project tree created by VS2019
templates for ASP.NET Core MVC App:
Connected Services
Dependencies
Properties
wwwroot
Controllers
Models
Views
appsettings.json
Program.cs
Startup.cs
Project Files and Folders Description
Connected Services—detail about all the service references
added to the project. e.g.; Access to Cloud Storage of Azure Storage
or Mobile services (to perform CRUD with Azure Table)
Source: Pro ASP.Net Core MVC 2, Adam Freeman, 7th Edition 2017, Apress
Summary
Overview of ASP.NET Core Application
Lecture 19
Fayyaz Muhammad
Assistant Professor
Understanding Models
Understanding Views
Understanding Controllers
DotNetTricks: https://www.dotnettricks.com/learn/aspnetcore
CodeMaze: https://code-maze.com/getting-started-with-asp-net-core-mvc/
TEKTUTORIALHUB: https://www.tektutorialshub.com/asp-net-core/asp-net-core-building-first-app/
Wikipedia: https://en.wikipedia.org/wiki/
Model–view–controller (MVC)
MVC—software design pattern (Architectural Pattern)
MVC—common pattern for designing apps that have UIs
MVC—Purpose is to separate internal representations of
information from the ways information is presented to and
accepted from the user
Web Apps need combining several technologies e.g., databases, HTML, and
executable code usually split into a set of tiers or layers
Logic that handles user requests and input is contained only in controllers
Source:
ASP.NET Core in Action
By Andrew Lock, 2018
Manning Publications Co
Understanding Models
The model should
Contain the domain data
Contain the logic for creating, managing, and modifying the domain
data
Provide a clean API that exposes the model data and operations on it
All the Model classes reside in the Model public int Age { get; set; }
}
folder
Types of Model
Several categories based on how and where they are used:
Domain Model—also referred to as the entity model or data model
the objects that represents the data in the database
one to one relationship with the tables in the database
Related to DAL—Retrieved from the database or persisted to the database by DAL
View Model
the objects which hold the data that needs to be shown to the user
related to the presentation layer of application
defined how the data is presented to the user rather than how they are stored
Edit Model—also referred to as Input Model
represents the data that needs to be presented to the user for modification/inserting
UI Requirement—for Editing can be different from the model required for Viewing
Understanding Views
View—consists of standard HTML Pages / JavaScript and CSS
ASP.NET Core MVC Views—.cshtml files that use the C# and HTML
along with Razor markup
Razor markup—code that interacts with HTML markup to produce a
web page
View files are grouped into folders named for each of app's controllers
that are stored in a Views folder at the root of the app
Views should
Contain the logic and markup required to present or capture data
to/from user
Logic should be simple and use sparingly
Views should not
Contain complex logic (better to place in a controller)
Contain logic that creates, stores, or manipulates the domain model
Understanding Controllers
Controller—just a class derived from the base class
System.Web.Mvc.Controller
Base Controller class—contains helper methods that can be used
for various purposes
Should contain the actions that provide
the business logic required to update the model based on user
interaction
the data that view display to user
Source: https://www.tutorialsteacher.com/mvc/action-method-in-mvc
Demo Application
In Demo Application we will discuss:
How to Create Models?
How to Create Views?
How to Create Controls?
How to use Model in Controller and how to Use Model
in View?
How Model, View and Controller Interact?
What are action methods and Action Verbs?
Using If statement in Controller and View with Razor
Working of Lists
Summary
Model View Controller (MVC) Pattern
Understanding Models
Understanding Views
Understanding Controllers
Lecture 20
Fayyaz Muhammad
Assistant Professor
Action Selector
Action Verbs
Action Results
Action Filters
Razor Syntax
A Demo Application Describing the Razor Syntax and Strongly Typed Views
Summary of Last Lecture
Model View Controller (MVC) Pattern
Understanding Models
Understanding Views
Understanding Controllers
DotNetTricks: https://www.dotnettricks.com/learn/aspnetcore
CodeMaze: https://code-maze.com/getting-started-with-asp-net-core-mvc/
TEKTUTORIALHUB: https://www.tektutorialshub.com/asp-net-core/asp-net-core-building-first-app/
Wikipedia: https://en.wikipedia.org/wiki/
Action Method
Controllers—the classes having a set of public methods called
actions (action methods).
Action methods—handle the incoming HTTP Requests
Invoked from the Web via some URL to perform an action when
you enter a particular URL in your browser address bar
http://localhost/Product/Index/3
Action Responsibility
Confirm the incoming request is valid
RedirectResult
RedirectToRouteResult
FileResult
ContentResult
StatusCodeResult
NotFoundResult
HttpUnauthorizedResult
Action Result Helper Methods
Action Results—have
helper method defined in
the Controller base class.
Usually, these method
names have the word
“Result” stripped away
E.g.
Content for ContentResult
View for ViewResult
Source: https://www.tutorialsteacher.com/mvc/action-method-in-mvc
Base Controller class—contains different methods, which automatically returns particular
type of result as shown in the below table
Result Class Description Base Controller Method
ViewResult Represents HTML and markup. View()
EmptyResult Represents No response.
ContentResult Represents string literal. Content()
FileContentResult, Represents the content of a file File()
FilePathResult,
FileStreamResult
JavaScriptResult Represent a JavaScript script. JavaScript()
JsonResult Represent JSON that can be used in AJAX Json()
RedirectResult Represents a redirection to a new URL Redirect()
RedirectToRouteResult Represent another action of same or other controller RedirectToRoute()
PartialViewResult Returns HTML PartialView()
HttpUnauthorizedResult Returns HTTP 403 status
Filters in ASP.NET Core
Filters—allow code to be run before or after specific stages in the
request processing pipeline
Filter—is custom class where you can write custom logic to execute
before or after an action method executes.
Filters—applied to an action method or controller
Filters—configured globally, per-controller or per-action
Built-in filters handle tasks such as:
Authorization
Response caching
run only when the action method has executed successfully and
the output.
Razor Code Blocks
Razor Code blocks—start with @ symbol followed by curly
braces
can be created anywhere in the markup using @ { }
can be used to manipulate a model, declare variables, and set
local properties on a view etc.
doesn't emit anything into the output means it is not
rendered like C# expressions
can use HTML tags directly, without placing them in literals
should not use it for business logic
Comment in Razor
Razor Code blocks—use the same syntax as we use in the C#:
For single line: //
For multiple line: /* and */
HTML with other code—use the razor comment block that starts
with @* and ends at *@:
@*
<h3>Inline expression</h3>
This is @UserName here.
<h3>Code Expression</h3>
<p>Total is @(val1 + val2)</p>
*@
How Does it Work?
Razor web pages—described as HTML pages with two kinds of
content: Client content and Server Code (Razor code)
Client contents—HTML markup, style information such as CSS, maybe
some client script such as JavaScript, and plain text
Razor Code—C# Expressions, Conditional Statements, Loops and
variable declarations
@ enables to intermingle HTML elements with code snippets that
perform some kind of work
@ provides a signal to the server that the following item is to be
processed as code When the server reads the page, it runs the Razor
code first, before it sends the HTML page to the browser and after
executing the code a static HTML is sent to the Browser
Razor Syntax Examples
<!-- Single statement blocks -->
@{ var total = 7; }
@{ var myMessage = "Hello World"; }
<!-- Inline expressions -->
<p>The value of your account is: @total </p>
<p>The value of myMessage is: @myMessage</p>
<!-- Multi-statement block -->
@{
var greeting = "Welcome to our site!";
var weekDay = DateTime.Now.DayOfWeek;
var greetingMessage = greeting + " Today is: " + weekDay;
}
<p>The greeting is: @greetingMessage</p>
Views Types
Data from the controller action method to a view can be passed in following
ways:
ViewBag
ViewData
TempData
Strongly typed model object
Loosely Typed Views—data from controller action method is passed using
ViewBag, TempData or ViewData to a View
Strongly typed Views—a model object (view model) is passed from
controller action method as a parameter to the view
provides compile-time error checking as well as intellisense support
are created by specify the type of model in the view by using @model
directive
Strongly Typed Views
A view that uses the @model expression to specify a type is known as a strongly typed
view
the @model expression declares the type of the model object passed to the view from
the action method.
@model allows to refer to the methods, fields, and properties of the view model object
through @Model
The @ sign indicates that the parsing will be done through Razor.
View Discovery
How Controller knows exactly which of the Views to return for a
specific Action?
View Discovery - a process where ASP.NET MVC determines which
view to use, without forcing you to specify
Unless a specific view file is specified, the Razor View Engine uses the
default convention to locate a view i.e.
Looks for a controller-specific view first (with the same name as action
method with the addition of the cshtml file extension (file type used by
the Razor view engine) as Views are stored by convention in the views
folder grouped by the name of the controller they are associated with
then looks for matching view name in the Shared folder which is the
location where views that are shared between controllers are stored.
View Discovery…
View discovery searches for a matching view file in:
1. Views/<ControllerName>/<ViewName>.cshtml
2. Views/Shared/<ViewName>.cshtml
For example: Views/Home/Index.cshtml
Views/Shared/Index.cshtml
A view file path can be also be provided, instead of a view name. In this case, the
.cshtml extension must be specified as part of the file path. The path should be
relative to the application root
(and can optionally start with “/” or “~/”).
For example: return View("Views/Home/About.cshtml");
A relative path can also be used to specify views in different directories without
the .cshtml extension. Inside the HomeController, you can return the Index view
of your Manage views with a relative path:
return View("../Manage/Index");
Be aware of the following when using the Razor:
You can write code that makes decisions and repeat (loop)
Lecture 21
Fayyaz Muhammad
Assistant Professor
Route Properties
Configuring Routes
Routes Examples
URL Generation
Tag Helpers
Layouts
Navigation Structure
A Demo Application Describing the Routing along with the Tag Helpers and
the Layout
Summary of Last Lecture
Action Method
Action Selector
Action Verbs
Action Results
Action Filters
Razor Syntax
DotNetTricks: https://www.dotnettricks.com/learn/aspnetcore
CodeMaze: https://code-maze.com/getting-started-with-asp-net-core-mvc/
TEKTUTORIALHUB: https://www.tektutorialshub.com/asp-net-core/asp-net-core-building-
first-app/
Wikipedia: https://en.wikipedia.org/wiki/
Routing in ASP.NET Core
How does the controller know to respond to the URLs like:
http://websitedomain/Guest/Index
How does the server know to call a method on that particular controller when
app receive a request?
The server is able to determine what action to take based on the routing
configuration
Routing engine— is one of the most important parts of the MVC Architecture
that decides what controller to invoke for a particular request
Routing Responsibilities
Routing—is not specific to any language or framework. It is used
in almost all MVC frameworks, though it might be implemented
differently
actions
How routing works?
How routing in ASP.NET Core works:
When a new request arrives, the routing middleware parses the incoming URL
A matching route is searched in the RouteCollection
If a matching route is found, control is passed to the RouteHandler
If a matching route is not found, the next middleware is invoked
RouteCollection—is the collection of all the Routes in the App
An app maintains a single in-memory collection of Routes that are added to this
collection when the application starts
RouteCollection—is defined in the Microsoft.AspNetcore.Routing
namespace and comprises of a collection of Routes.
RouteHandler—is a class that implements the IRouteHandler interface is
responsible for handling the incoming request
What is a Route?
Route—is a rule that is used to decide how a request is handled
Route—defines or contains URL pattern and handler information
Routes—are responsible for determining which controller method
to execute for a given URL
Routes—are used by ASP.NET Apps to go to the controller action
All the configured routes of an application stored in
RouteTable or RouteCollection and will be used by Routing
engine to determine appropriate handler class or file for an
incoming request
Properties of Route
A route consists of the following properties that are use to
modify the behavior or content of a given route and these
properties are configured in the apps
Route Name
URL Pattern
Defaults
Constraints
Route Name
Route Name—is used as a specific reference to a given
route.
Route Parameters can have default value like {controller=Home}, where Home
is the default value for the controller. An equals = sign followed by a value after
the Route Parameter name defines a default value for the parameter.
Routes can have the Constant segments as shown in this route:
admin/{controller=Home}/{action=Index}/{id?}
Here admin is a Constant and must present in the requested URL.
The ? in {id ?} indicates that it is optional. A question mark ? after the route
parameter name defines the parameter as optional
URL Pattern Structure
You can also have multiple patterns that all point to the same
The controller and action values in the route are not case-sensitive.
Configure Routes in ASP.NET Core MVC
Every MVC application must configure (register) at least one route, which is configured by
MVC framework by default.
When we create a new ASP.NET Core MVC application using the default template, the
application configures a default routing. Let’s create a new project have a look at the
startup.cs class. We can see that the application has configured a default routing in the
Configure() method:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
Inside the call to UseEndpoints(), we use the MapControllerRoute() method to
create a route by giving the name default.
When the ASP.NET MVC application launches then the application registers one or
more patterns with the framework's route table to tell the routing engine what to do
with any requests that matches those patterns.
Routing Types
Two different ways by which we can set up the routes (templates):
Convention-based routing—Creates routes based on a series of
conventions, configured in route template in Startup file how at runtime
route will map requests to controller and action methods
Used for controllers returning HTML
Attribute routing—Creates routes based on attributes placed on
controller and actions. These attributes will define the mapping to the
controller’s actions.
Used for Web API controllers where possible
Mixed Routing—These two routing systems can co-exist in the same
project
Since it's not possible to define attribute route for each and every action
or controller. In that case, Convention-based Routing will help you.
However, if you define attribute routing on an action, then convention
based routing cannot be used on that Action.
How to configure attribute-based routing
In attribute-based routing—Routes are added using the Route Attribute
on the controller and Action
Route Attribute—takes three arguments, URL Pattern, name and order
Here’s how you can configure routes using attributes You can also specify multiple routes on your
on your controller’s action methods: action method. Here's an example:
public class AuthorsController : Controller public class AuthorsController : Controller
{ {
[Route("Index")] [HttpGet("")]
public IActionResult Index() [HttpGet("index")]
{ public IActionResult Index()
return View(); {
} return View();
} }
}
Parameters to Controller Action Method
app.UseMvc(routes => {
routes.MapRoute("default",
"{controller=Home}/{action=Index}/{id?}");});
Endpoints—are defined in the app and configured when the app starts
Built-In Tag Helpers—are pre-built in the Core Framework and are used
internally by the Razor. They perform common tasks like:
creating forms, generating URLs for forms using the application’s routing
configuration, showing validation messages, binding elements with Model,
Tag Helpers for Form, Input, Select, Label, Anchor, Text Area elements, CSS, JS
and Cache
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
The code above uses the wildcard syntax (“*”) to specify that all Tag
Helpers in the specified assembly (Microsoft.AspNetCore.Mvc.TagHelpers)
The type, id & name attributes are automatically derived from the model
property type & data annotations applied on the model property
Anchor Tag Helper
Anchor Tag Helper—targets the HTML anchor (<a>) tag which is used to
generate relative links from the values passed to various custom attributes.
It can also used to generate absolute URLs to external resources.
Some of the available attributes are:
asp-controller: name of the MVC controller to use
However, that is often very cumbersome and error-prone especially if you have a
large number of views.
The layouts page—in ASP.NET Core helps us to define the common user
interface elements like header, footer & navigation menu etc. on the page at one
place and use it everywhere else.
Location of the Layout Page—The Views folder also contains a shared folder,
where views shared across multiple views are shared. Since layouts are shared
across the other views, they are stores in the Views/Shared folder.
The layouts page…
Layouts reduce duplicate code in views The layout files for new ASP.NET Core projects
created with the templates are:
Common HTML structures such as
scripts and stylesheets are also
frequently used by many pages within
an app.
All of these shared elements may be
defined in a layout file, which can then
be referenced by any view used within
the app.
By convention, the default layout for an
ASP.NET Core app is named as:
_Layout.cshtml
Default Layout File
It sets up the default layout page for all the views in the folder and its
subfolders using the Layout property.
You can assign a valid path of any Layout page to the Layout property.
You can set the Layout property in the individual view also, to override
default layout page setting of _ViewStart.cshtml
_ViewImport.cshtml
_ViewImport.cshtml—is a special kind of file that MVC knows about this file and
will pick it up during execution. No need to register the file anywhere, just put it in a
folder where the views are stored.
View imports file—has a very specific role. It is used to include the common
namespaces (using statements) so we do not have to include them in every view
that needs those namespaces.
There can be an overall view imports file in the Views folder as well. That will be
applied to every single view within the Views folder and its subfolders
Specifying the Layout to Use in the View
@{ @{
Layout = "_Layout";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<p>Here goes the content</p> }
Route Properties
Configuring Routes
Routes Examples
Tag Helpers
Layouts
Navigation Structure
A Demo Application Describing the Routing along with the Tag Helpers and
the Layout
Thank You
ITEC 4116
Advance Web Application Development
Lecture 22
Fayyaz Muhammad
Assistant Professor
Model Validation
Route Properties
Configuring Routes
Routes Examples
URL Generation
Tag Helpers
Layouts
Navigation Structure
DotNetTricks: https://www.dotnettricks.com/learn/aspnetcore
CodeMaze: https://code-maze.com/getting-started-with-asp-net-core-mvc/
TEKTUTORIALHUB: https://www.tektutorialshub.com/asp-net-core/asp-net-core-
building-first-app/
Model Binding
Web Apps—very basic job is to collect and process user input data
with business logic and save to the database
Web Apps—collect data in the View (HTML Forms) and process
through the Controller action methods
There are various ways to gather form value in the controller
Model binding—is the process of mapping the data posted over an
HTTP request to the parameters of the action method in the Controller
HTTP Request—can contain data in various formats such as:
in the HTML form fields
could be part of the route values
could be part of the query string
in the body of the request
Model Binding …
ASP.NET Core model binding—mechanism allows us easily
bind those values to the parameters in the action method. These
parameters can be of the primitive type or complex type.
On form submission, the values in the form fields are automatically
mapped by model binder to the object of the action method of the
controller without having to inspect, parse, and process the data
directly
Default model binder isn’t case sensitive, so a binding value of
QTY=50 will happily bind to the qty parameter.
Model binding advantages:
You reduces repetitive code
Model binder— also looks explicitly for the data from the following sources:
Request Body
Request Header
Services
Model binding
Model validation
Process
Source:
ASP.NET Core in Action
By Andrew Lock, 2018
Manning Publications Co
Model Binding Example
Source: https://www.tektutorialshub.com/asp-net-core/asp-net-core-model-binding/
ModelState
If Model binder fails to bind the incoming Request data to
the corresponding model property, then it does not throw
any error but fails silently.
model.Name = Request.Form["Name"].ToString();
model.Rate = Convert.ToDecimal(Request.Form["Rate"]);
model.Rating =Convert.ToInt32(Request.Form["Rateing"]);
Similarly you can use the Request.Headers collection to access the values
present the HTTP Headers
Accessing the Request Route Data
Accessing the Route Data directly
To Access the route you need to Override the OnActionExecuting method
as shown below:
using Microsoft.AspNetCore.Mvc.Filters;
public override void OnActionExecuting(ActionExecutingContext context)
{
string id = context.RouteData.Values["id"].ToString();
base.OnActionExecuting(context);
}
The need for validation
Data can come from many different sources in your web apps:
you could load it from files
read it from a database
you could accept values that a user typed into a form in requests
How will come to know that the data is valid:
Often the data entered by the user is not valid
Not properly formatted
Entered data may contain a typo or user may intentionally enter the
inappropriate data
Numbers might need to be in a particular range
Some values may be required but others are optional
Hence, we need to validate the user input before storing it in the
database
Model Validator
The Model needs to be validated for the correctness.
ASP.NET Core Provides:
HTML helpers—to do the input validations
Model Validator—which uses the validation attributes to
validate the model, which makes our task easier.
Validation occurs after model binding but before the action method
executes
The action method executes whether or not validation is successful
These validations can be done at:
the client side before sending data to the server
the server side when the data is received from the client
Importance of client-side Validation
Client Side Validation provides better User experiences
Since the validation happens in the client’s browser, the Response is faster
and immediate
Since there is no HTTP Request/response round trip involved in the
validation this saves precious server resources and bandwidth
—are capable of performing validation on the server side as well as on the client side
—are automatically detected by the ASP.NET and uses them to validate data during the
model-binding process
—are easy to use and the code becomes much cleaner as compared to normal ASP.NET
validators
List of Data Annotation Attributes
There are several data annotations provide by ASP.NET. Following are
some of the frequently used having a self descriptive name:
Required StringLength
Regular Expression UrIHint
Range DataType
EmailAddress StringLength
DisplayName MaxLength
DisplayFormat MinLength
Scaffold DataType
Data Annotations Attributes Description
Required—specifies that the value is mandatory and cannot be skipped
Syntax: [Required(ErrorMessage="Please enter name"), MaxLength(30)]
Syntax: [MaxLength(3)]
There are two Validation Tag Helpers which display the validation
messages to the user (on the client side):
When you submit the form with an empty name field. The following HTML is generated.
Note that the <span> element now contains the error message and field-validation-error
class is applied to it.
<label for="Name">Name</label>
<input type="text" class="input-validation-error" data-val="true" data-val-required="The Name
field is required." id="Name" name="Name" value="" />
<span class="field-validation-error" data-val msg-for="Name" data-val msg-replace="true">The
Name field is required.</span>
Validation Summary Tag Helper
Validation summary tag helper—targets the HTML <div> element and is
used to display the all of forms validation error messages at one place. Each
error message is displayed in an unordered list.
asp-validation-summary tag helper—is placed at the top of the form so as
to display the error messages
You need to specify three values to asp-validation-summary tag helper:
All—This Option displays all the validation errors.
<div asp-validation-summary="All"></div>
ModelOnly—This Option displays the Model level validation error. The
Property Model errors are not displayed. Use this option if you are
displaying the property validation error using the asp-validation-for tag
helper: <div asp-validation-summary="ModelOnly"></div>
None—This Option will not display any error message
Unobtrusive Client Side Validation in ASP.NET Core
Client side validation can be performed in many ways. You can:
Use Javascript Libraries like JQuery validation and Javascript unobtrusive library
This library is built over the top of jquery.validate.js library, which in turns uses the
jQuery
These scripts are added in the layout file (_Layout.cshtml), which defines the layout of our
application so that they are available for all the views
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script>
View model— is a best approach for passing data from a controller to a view. It’s
the standard mechanism for passing data between the controller and the view
We have explained this in our previous lectures
Weakly Typed Data—Two approaches to passing a weakly typed data into the
views:
ViewData
ViewBag
Passing data into Views …
ViewData—is a dictionary of objects with string keys that can be used to
pass arbitrary data from the controller to the view
ViewData—is the standard mechanism for passing data to a layout from a
view. It is a convenient way of passing data from a view to the layout.
ViewBag—is a version of the ViewData that uses C# dynamic objects
instead of string keys. It’s a dynamic wrapper around the ViewData object,
so you can use it in place of ViewData if you prefer dynamic to Dictionary
When you invoke the View method in the Controller Action method, the
ViewData and ViewBag is automatically passed to the View
In general you should use the mechanisms in the following order:
View Model, ViewData and ViewBag
Clearly Differentiate between ViewData and ViewBag
Exercise
Summary
Model Binding
Model Validation
Lecture 23
Fayyaz Muhammad
Assistant Professor
Model Validation
DotNetTricks: https://www.dotnettricks.com/learn/aspnetcore
CodeMaze: https://code-maze.com/getting-started-with-asp-net-core-mvc/
TEKTUTORIALHUB: https://www.tektutorialshub.com/asp-net-core/asp-net-core-
building-first-app/
State Management
HTTP protocol—on which all web apps work is a stateless protocol
HTTP requests—are by default, independent messages that don't
retain user values or app states
State—simply means an interaction between the user and the server
By stateless, it just means that information is not retained from one
request to another.
Each HTTP request does not know about the previous request
We need to take additional steps to manage state between the
requests:
E.g.: If you are redirecting from one page to another page, then you have
to maintain or persist your data so that you can access it further
State management—is the process by which developers can
maintain state and page information over multiple request for the
same or different pages in web application.
State Management Approaches
State can be stored by using several approaches:
Storage approach Storage mechanism
Cookies HTTP cookies. May include data stored using
server-side app code
Session state HTTP cookies and server-side app code
TempData HTTP cookies or session state
Query strings HTTP query strings
Hidden fields HTTP form fields
HttpContext.Items Server-side app code
Cache Server-side app code
Cookies
Cookies—store data across requests
Cookie—is essentially a physical, simple, text file that is stored by a
client (mostly a browser) and linked to a specific website.
The client grants this page permission to read the information
stored in the file during each subsequent request. This actually
allows the server or even the client itself to store information for
later use
Cookies—store data in the user’s browser
Cookies—size should be kept minimum as browsers send cookies
with every request that is why most browsers restrict cookie size to
4096 bytes and only a limited number of cookies are available for
each domain i.e., 20.
Cookies…
Cookies—can be easily tempered or deleted by users
Cookies—can also expire on their own
Cookies—should not be used to store sensitive information and their
values should not be blindly trusted or used without proper
validations.
Cookies—are often used to personalize the contents for a known user
Cookies—store some basic information like user’s name or an
identifier to access the user’s personalized settings such as their
preferred color theme
An App doesn’t retain empty sessions. The session must have at least one
value set to persist the session across requests. When a session isn't retained,
a new session ID is generated for each new request
An app retains a session for a limited time after the last request
An app either sets the session timeout or uses the default value of 20 minutes
Session State Behavior …
Session state—is ideal for storing user data that are specific to a
particular session but doesn’t require permanent storage across
sessions
An app deletes the data stored in session either when we call the
ISession.Clear implementation or when the session expires
There’s no default mechanism to inform the app that a client has closed
the browser or deleted the session cookie or it is expired
web app is part of web farm and you don't want sticky sessions
TempData Providers…
Session state based TempData—storage is enabled by using
middleware and you also need to change the default provider
HTTP-based caching
In-memory caching
Distributed caching
HTTP-based Caching…
HTTP-based Caching—Caches data at web browser's end on the
client
HTTP 1.1 Caching specification—describes how Internet caches
should behave
Primary HTTP header used for caching is Cache-Control, which is
used to specify cache directives.
The directives control caching behavior as requests make their way
from clients to servers and as responses make their way from
servers back to clients.
Requests and responses move through proxy servers, and proxy
servers must also conform to the HTTP 1.1 Caching specification.
HTTP-based Caching…
Cache control header—are used to set browser caching
policies in requests that originate from the clients as well as
responses that come from the server. E.g.:
cache-control: max-age=90 implies that the server response is
valid for a period of 90 seconds. Once this time period elapses,
the web browser should request a new version of the data
HTTP Based Caching—reduces the number of requests a client
makes to the web server, as any subsequent requests will be
entertained by the cache instead of the web server
However, once the response is cached in the browser, it will only
expire once its assigned caching time is up, and cannot be
cleared when needed.
In-memory Caching
In-memory caching—caches data in the server's memory, using
ASP.NET Core’s own internal caching provider.
In-memory caching—is suitable for a single server or multiple servers
using sticky sessions.
Sticky sessions—means that the requests from a client are always
routed to the same server for processing. This option is more flexible
for caching responses as ASP.NET Core provides Cache Tag Helper.
Cache Tag Helper—allows adding tags to specify which contents from
MVC view of the app should be cached. Since this is in-proc, you can
restart the ASP.NET engine to clear the cache when required.
In-memory caching—boosts performance and scalability of
ASP.NET Core application’s by storing infrequently changing data in the
server’s memory
Distributed Caching
Distributed Caching—caches data in memory if the application is
hosted in a web farm. The cache is distributed across all the servers of
the web farm and any server can respond to the client if requested
data is available in cache.
Distributed cache—is external to an application
Similar to In-Memory Caching, Distributed Cache Tag Helper allow
specifying exact views which need to be cached.
Distributed Cache Tag Helper—caches the content from an MVC
view or Razor Page in distributed cloud or web farm scenarios with
the Distributed Cache Tag Helper.
Distributed Cache Tag Helper—uses SQL Server, Redis, or NCache to
store data
Distributed Caching …
Distributed cache—has several advantages over other caching scenarios
where cached data is stored on individual app servers.
Use TempData to pass data from a controller action method to another or a View.
Using Hidden Fields to store data that are not displayed on a page.
Fayyaz Muhammad
Assistant Professor
jQuery
ADO.NET
ADO.NET Components
Connection String
DotNetTricks: https://www.dotnettricks.com/learn/aspnetcore
CodeMaze: https://code-maze.com/getting-started-with-asp-net-core-mvc/
TEKTUTORIALHUB: https://www.tektutorialshub.com/asp-net-core/asp-net-core-
building-first-app/
AJAX
JavaScript—is a programming language that makes it possible to manipulate
the contents of web pages after they have loaded.
AJAX—stands for Asynchronous JavaScript and XML
AJAX—refers to a web communications approach that started to become
popular in 2005 and 2006
AJAX—primary purpose is to enable communications between the user’s
browser and the server without having to do a full page refresh using
XmlHttpRequest
AJAX—is about using ability of JavaScript to send asynchronous http request
and get the xml data as a response (also in other formats) and update the part
of a web page (using JavaScript) without reloading entire web page
AJAX—is usually is associated with server-side applications
E.g.: you can use it to fetch information and display it on the page or to submit a
form for processing, all without changing the full page in the browser.
jQuery
Each Browser supports HTML, CSS and JavaScript differently
Most of the incompatibilities between browsers are in their DOM
implementations
Editor—You can use any JavaScript editor to write jQuery code including following:
Notepad
Visual Studio
Eclipse
Aptana Studio
Ultra edit
DOM Manipulation: You can manipulate DOM elements using various built-in jQuery
functions. E.g.: adding or removing elements, modifying html content, CSS class etc.
Special Effects: You can apply special effects to DOM elements like:
show or hide elements, fade-in or fade-out of visibility, sliding effect, animation
Events: jQuery library includes functions which are equivalent to DOM events like:
click, dblclick, mouseenter, mouseleave, blur, keyup, keydown etc.
These functions automatically handle cross-browser issues without writing extra code
jQuery Important Features
AJAX: jQuery also includes easy to use AJAX functions to load data from servers
without reloading whole page.
Easy to learn: jQuery is easy to learn because it supports same JavaScript style coding.
Write less do more: jQuery provides a rich set of features that increase developers'
productivity by writing less and readable code.
Context—is optional
Start Using jQuery…
Standard jQuery Syntax—a jQuery statement typically starts with
the dollar sign ($) and ends with a semicolon (;).
jQuery—typically interacts with the DOM elements and performs
some operation on them. Therefore, we need to detect when the DOM
is loaded fully, so that the jQuery code starts interacting with DOM
without any error.
It is advisable to use jQuery after DOM is loaded fully.
jQuery—includes built-in function ready(), which detects whether a
particular element is ready (loaded) or not.
Use jQuery ready() function to make sure that DOM is loaded fully.
Start Using jQuery…
window.onload() & $(document).ready() is different:
window.onload() is fired when the whole html document is loaded with
images and other resources,
whereas jQuery ready() function is fired when DOM hierarchy is loaded
without other resources
$(document).ready()—doesn't wait for images to be loaded. It gets called as soon
as DOM hierarchy is constructed fully.
First thing you need to write before writing any jQuery code. You always need to
check whether a document is ready or not in order to interact with the DOM safely.
Selecting Elements with jQuery
Before applying any action on the HTML Element, you need to find or
select the target HTML Element
jQuery—supports almost all the selectors defined in the latest CSS3
specifications, as well as it has its own custom selectors.
jQuery—selects elements in the following ways:
Selecting Elements by ID—use the ID selector to select a single element
with the unique ID on the page
Selecting Elements by Class Name—can be used to select the elements
with a specific class
Selecting Elements by Name—can be used to select elements based on
the element name
Selecting Elements by Attribute—used to select an element by one of its
HTML attributes, such as a link's target attribute or an input's type
attribute, etc.
jQuery AJAX methods
Following table lists all the jQuery AJAX methods that are used to
request or load the external data directly into the selected HTML
elements of your web page!
jQuery AJAX Methods Description
ajax() Sends asynchronous http request to the server.
get() Sends http GET request to load the data from the server.
Post() Sends http POST request to submit or load the data to the server
getJSON() Sends http GET request to load JSON encoded data from the
server
getScript() Sends http GET request to load the JavaScript file from the server
and then executes it.
load() Sends http request to load the html or text content from the
server and add them to DOM element(s).
jQuery AJAX Events
Following are the jQuery AJAX events which will be fired based on the state of
the AJAX request:
$("#myButton").click(function(){
$("#myDiv").load('Sample.html')
})
});
jQuery get() method
get() method—sends asynchronous HTTP GET request to the server
and retrieves the data
jQuery