Вы находитесь на странице: 1из 569

ITEC 4116

Advance Web Application Development

Lecture 01

Fayyaz Muhammad
Assistant Professor

University of Education Lahore, Multan Campus


ITEC 4116
Advance Web Application Development

Lecture 01
Course Introduction

Advance Web Application Development


Course Objectives
 The main objectives of this course are to:
 Describe the Microsoft web technologies stack and select an
appropriate technology to use to develop any given
application

 Describe how to develop and deploy an ASP.NET MVC web


applications
Course Information
 Prerequisites:
 Fundamentals of Computer Programming
 Web Technologies

 Course Title: Advance Web Application Development


 Course Code: ITEC4116
 Credit Hours: 3(2+1)

 Note: There will be 32 Lecturers excluding exams


Evaluation Components
 Following are the components of the evaluation:
 Assignments
 Quizzes
 Presentations
 Class Discussion
 Mid Term Exam
 Terminal Exam
 Practical
Course Evaluation
 Total Marks: 100
 Sessional Marks : 20% (Quizzes, Assignment, Presentation, Class discussion)
 Mid Term Exam: 20%
 Practical:15%
 Final Exam (Terminal Exam): 45%
Note: All Course will be included in the Final Exam
There will be no choice in the mid term and final exams.
Text & other instructional material
 Text Book(s)
 Pro ASP.Net Core MVC 2, Adam Freeman, 7th Edition 2017, Apress.

 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

 Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/

 World Wide Consortium (W3C): https://www.w3.org/standards/webdesign/

 HTML 5 Tutorial : https://www.w3schools.com/asp/webpages_intro.asp

 CSS Tutorial: https://www.w3schools.com/css/default.asp

 Java Script: Tutorial: https://www.w3schools.com/js/default.asp

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

 MS Visual Studio (Current Version) Community Edition

 MS SQL Server Express or Developer (Current Version)


Course Outline
Following is the main outline for the course:
 Exploring ASP.NET MVC

 Designing ASP.NET MVC

 Developing ASP.NET MVC Controllers

 Developing ASP.NET MVC Views

 Structuring ASP.NET MVC Web Applications

 Applying Styles to ASP.NET MVC Web Applications


Course Outline…
 Building Responsive Pages in ASP.NET MVC Web Applications

 Using JavaScript and jQuery for Responsive MVC Web Applications

 Controlling Access to ASP.NET MVC Web Applications

 Building a Resilient ASP.NET MVC Web Application

 Implementing Web APIs in ASP.NET MVC Web Applications

 Handling Requests in ASP.NET MVC Web Applications

 Deploying ASP.NET MVC Web Applications


Methods of instructions

 Lectures
 Demonstration and Hands on exercises
 Class Discussion
Learning Objectives

 Understand the growing needs of Web Applications

 Explain What is Web Application

 Web Applications and other Applications

 Web Development

 Key advantages of using Web Applications


Introduction
 Whenever you need some information, some new ideas, or have
some problems, you generally try to google.
 A typical internet user visits a lot of website for satisfying his
day to day business, entertainment, education or training
needs. The Internet is a very big place, but have you ever
thought:
 How these websites actually work?
 How are they built?
 How do browsers, computers, and mobile devices interact with the web?
 What skills are necessary to build a website?
 What technologies are required to build a website?
Web Application
 Computer software, or simply software
 A collection of data or computer instructions that tell the computer how to
work
 Application software (App for short)
 A program or group of programs designed for end users. Examples of an
application:
 A word processor
 A spreadsheet
 An accounting application
 A web browser
 An email client,
 A media player
 A file viewer, an aeronautical flight simulator, a console game or a photo editor.
Web Application…

 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

 eCommerce / Shopping Cart Applications

 Interactive Games, Online Training

 Online Polls, Blogs

 Online Forums

 Content Management Systems


Understanding Web Applications
 It’s difficult to understand what web development is if you don’t
have at least a general idea of how the web works.
 To understand the concept of a web application:
 You need a web server to handle the user requests,
 An application server to perform the required tasks and,
 A database to store the information or retrieve information.
Understanding Web Applications
 The below points explain Web App processing briefly:
 User sends a request to the web server through the Internet using a web browser or an
application’s user interface.

 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

 In our daily life, we use various applications to perform our routine


activities
 Following are the other applications:
 Desktop Apps
 Mobile Apps
 Web Services
 Websites
Desktop or Native App VS Web App
 As previously defined all conventional software applications are desktop
native applications
 For example
 Microsoft Word, a common word-processing app that is a desktop app.

 Desktop apps or "mobile apps" run directly on a mobile device, just as a


conventional software application runs directly on a desktop computer after
installation, without a web browser (and potentially without the need for
Internet connectivity)

 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

 Web Apps are generally meant to solve a user problem


 Web Apps core intention is user input and interaction
 Web Apps will have a backend, a business logic, database,
authentication and more
Website VS Web App…
Example: A Restaurant’s Website and Web App:
 If it provides food menu, discounts and offers for a special occasion, a
picture gallery of its range or directions to the restaurant – it is a website.

 If it also provides additional features like ordering the food, customizing


your order, make an online payment, tracking the delivery, etc. all these
make it a web application
Web Site (Static vs Dynamic)
 Static Website
 that has web pages stored on the server in the format that is sent to a
client web browser. It is primarily coded in Hypertext Markup Language
(HTML); Cascading Style Sheets (CSS) are used to control appearance
beyond basic HTML.
 usually displays the same information to all visitors.
 Dynamic Website
 that changes or customizes itself frequently and automatically. Server-
side dynamic pages are generated "on the fly" by computer code that
produces the HTML (CSS are responsible for appearance and thus, are
static files).
Web Page
 A web page (also written as webpage) is a specific collection of
information provided by a website and displayed to a user in a
web browser.

 A website typically consists of many web pages linked together in


a coherent fashion. The name "web page" is a metaphor of paper
pages bound together into a book.

 These Web Pages are to be stored in the web servers connected to


the Internet, to be made available to others.
Web Services vs Web App
 World Wide Web Consortium (W3C) describes web service:
 A system of software allowing different machines to interact with each other
through network.
 Wikipedia describes web service:
 a service offered by an electronic device to another electronic device,
communicating with each other via the World Wide Web
 Web services achieve this task with the help of:
 XML (Extensible Markup Language)
 SOAP, (Simple Object Access Protocol)
 WSDL (Web Services Description Language)
 UDDI (Universal Description, Discovery, and Integration) open standards.
Web Services vs Web App …
 Web Services:
 can be used to transfer data between Web Applications

 can be accessed from any languages or platform.

 are meant for computers to read as Web App is meant for humans to read

 do not necessarily have a user interface , work as component in an application


Key benefits of web applications
 Some of the advantages of using web-based applications:
 Work from anywhere anytime enhances the productivity of the users
 No physical software to download, install, update or manage on computer or
mobile device
 No need to develop and test it on all possible operating system versions and
configurations
 Web based software is compatible with any device or platform
 It eliminates the compatibility issues as each user can access the same
version
 Increased security as web apps are deployed on dedicated servers which are
monitored and maintained by experienced server administrators
Web Development
 Web Development
 is the work involved in developing a website (static or dynamic) for the
Internet (World Wide Web) or an intranet (a private network)

 This work can range from developing a simple single static


page of plain text to complex web-based internet applications
(web apps), electronic businesses, and social network services.
Web Development
 Following tasks may include in web development:
 Web engineering
 Web design
 Web content development
 Client liaison, client-side/server-side scripting
 Web server and network security configuration
 E-commerce development or business logic development

 Web apps are trickier to develop as compared to desktop and


mobile apps
Summary
 Software Application extends to Web Application

 Working of Web Applications

 Web Apps VS Other Apps

 Advantages of the Web Apps

 Web Development
Thank You
ITEC 4116
Advance Web Application Development

Lecture 02

Fayyaz Muhammad
Assistant Professor

University of Education Lahore, Multan Campus


ITEC 4116
Advance Web Application Development

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

 Working of Web Applications

 Web Apps VS Other Apps

 Advantages of the Web Apps

 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 Internet carries a vast range of information resources and


services:
 The inter-linked hypertext documents and applications of the World Wide
Web (WWW)
 Electronic mail
 Telephony
 File sharing
Protocols
 Protocol
 Set of rules that governs the communications between computers on a
network

 TCP/IP—communication protocol as the bulk of the services we associate


with the Internet—e-mail, Web browsing, file downloads, accessing remote
databases—are built on top of both the TCP and IP protocols.

 SMTP supports transfer of e-mail between different e-mail servers

 FTP is used for transferring files between machines.


What is World Wide Web (Web)
 The World Wide Web (WWW), commonly known as the Web, is an information
system where documents and other web resources are identified by Uniform
Resource Locators (URLs, such as https://www.example.com/), which may be
interlinked by hypertext, and are accessible over the Internet.

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

 Internet is the infrastructure and WWW uses it for


communication
 WWW is what most people think of as the Internet. It is all the Web pages,
pictures, videos and other online content that can be accessed via a Web browser.
The Internet, in contrast, is the underlying network connection that allows us to
send email and access the World Wide Web.
Components of Web
 Web has the following general components:
 The Internet

 Information system

 Web resources

 Uniform Resource Locators

 Hypertext

 Hypertext Transfer Protocol

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

 HTTP Communication is also referred as:


 A request–response model i.e., a client-server model.

 HTTP uses reliable data-transmission protocols that is HTTPS


which is an advanced and more secure upgrade to HTTP
 Also good for you as an Internet application developer, because you don't have
to worry about HTTP communications
HTTP Methods/Request Methods
HTTP defines a set of request methods to indicate the desired action to be performed for a
given resource.

 Primary or most-commonly-used HTTP verbs (or methods, as they are properly called)
are:

 GET, POST, PUT, DELETE, and PATCH.

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

 DELETE—to delete the specified resource.

 PATCH — to apply partial modifications to a resource.


Hypertext
 Building blocks of the Web are web pages which are formatted in HTML and
connected by links called "hypertext" or hyperlinks and accessed by HTTP.
 Hypertext is text displayed on a computer display or other electronic
devices with references (hyperlinks) to other text that the reader can
immediately access.
 Hypertext documents are interconnected by hyperlinks, which are typically
activated by a mouse click, keypress set or by touching the screen.
 Hypertext is one of the key underlying concepts of the World Wide Web,
where Web pages are often written in the Hypertext Markup
Language (HTML)
 Hypertext enables the easy-to-use publication of information over
the Internet.
 Hypertext offers the advantage to select a word or phrase from text and thus
to access other pages that provide additional information related to that
word or phrase.
Web Resources
 Web servers host web resources that is a source of web content.
 A web resource, or simply resource, is any identifiable thing, whether digital,
physical, or abstract. Resources are identified using Uniform Resource
Identifiers
 Kinds of web resource:
 A static file on the web server's filesystem. These files can contain anything:
 Text files
 HTML file
 Microsoft Word files,
 Adobe Acrobat files,
 JPEG image files
 Movie files
 Any other format you can think of.
 Resources can also be software programs that generate content on demand.
Media Types
Multipurpose Internet Mail Extensions (MIME)
 The Internet hosts many thousands of different data types, HTTP carefully
tags each object being transported through the Web with a data format label
called a MIME type.
 Web servers attach a MIME type to all HTTP object data (resources)
 When a web browser gets an object back from a server, it looks at the
associated MIME type to see if it knows how to handle the object. Most
browsers can handle hundreds of popular object types:
 Displaying image files
 Parsing and formatting HTML files
 Playing audio files through the computer's speakers
 Launching external plug-in software to handle special formats.
Multipurpose Internet Mail Extensions (MIME)
 A MIME type is a textual label, represented as a primary object type
and a specific subtype, separated by a slash. For example:
 An HTML-formatted text document would be labeled with type text/html
 A plain ASCII text document would be labeled with type text/plain
 A JPEG version of an image would be image/jpeg
 A GIF-format image would be image/gif
 An Apple QuickTime movie would be video/quicktime
 A Microsoft PowerPoint presentation would be application/vnd.mspowerpoint
 There are hundreds of popular MIME types, and many more
experimental or limited-use types
Uniform Resource Identifier URI
 Each web server resource has a name (an HTML static web page or a PDF
document), so clients can point out what resources they are interested in.
The server resource name is called a Uniform Resource Identifier, or URI.
 A URI is a sequence of characters that identifies a logical or physical
resource.
 URIs are like the postal addresses of the Internet, uniquely identifying and
locating information resources around the world.
 the URI does not tell you how to find a resource. It’s a generic identifier
 Here's a URI for an image resource on UE Hardware store's web server:
http://www.UE-hardware.com/specials/SOS.pdf or Outline.gif
 Given the URI, HTTP can retrieve the object.
 Two types of URIs: Uniform Resource Locators (URLs) and Uniform
Resource Names (URNs)
Uniform Resource Locator (URL)
 The first flavor of URI is the Uniform Resource Locator, or URL
 A URL colloquially termed a web address, is a reference to a
web resource that specifies its location on a computer network
and a mechanism for retrieving it.
 A particular collection of web pages that belong to a specific
URL is called a website,
e.g., www.facebook.com, www.google.com, etc.
 A URL is a specific type of Uniform Resource Identifier (URI)
 Although many people use the two terms interchangeably
 URLs also used for file transfer (ftp), email (mail to), database
access (JDBC), and many other applications.
Uniform Resource Locator (URL)
 Most URLs follow a standardized format of three main parts:
 The first part of the URL is called the scheme, and it describes the
protocol used to access the resource. This is usually the HTTP protocol
(http:// ).

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

 A URN serves as a unique name for a particular piece of content,


independent of where the resource currently resides.

 These location independent URNs allow resources to move from place to


place. URNs also allow resources to be accessed by multiple network access
protocols while maintaining the same name. For example, the following
URN might be used to name the Internet standards document "RFC 2141"
regardless of where it resides (it may even be copied in several places):

urn:ietf:rfc:2141

 Unless stated otherwise, we adopt the conventional terminology and use


URI and URL interchangeably
Web Clients
 A web client is software that accesses a web server by sending an HTTP
request message and processing the resulting HTTP response.
 Most common Web Clients:
 Web browsers running on desktop or laptop computers
 Rarely used:
 Text-only browsers
 browsers running on cell phones
 browsers that speak a page (over the phone, for example) rather than displaying
the page.
 Some web clients are not designed to be used directly by humans at all.
 For example, software robots are often used to automatically crawl the Web and
download information for use by search engines (and, unfortunately, e-mail
spammers).
Basic Web Browser Functions
The browser must perform a number of tasks:

1. Reformat the URL entered as a valid HTTP request message.

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.

2. When a connection request is received, the server dedicates a “subtask”


to handling this connection.

3. The subtask establishes the TCP connection and receives an HTTP


request.

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

University of Education Lahore, Multan Campus


ITEC 4116
Advance Web Application Development

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.

 Aim is to automate the overhead associated with common activities


performed in web development.
Top 10 Frameworks for Web Applications
 Ruby on Rails: Language : Ruby
 Django: Language : Python
 Angular: Language : JavaScript
 ASP.NET: Language : C#
 METEOR: Language : JavaScript
 Laravel: Language : PHP
 Express: Language : JavaScript
 Spring: Language : Java
 PLAY: Language : Scala and Java
 CodeIgniter: Language : PHP
How to choose technology
 Depends:
 What is the type of content?
 Who is your audience?
 Who will modify your content?
 What are your Future Plans?
 Availability of technology?
 Your previous experience
 Portability and Data sharing
Web Application Architecture
 Describes the interactions between applications, databases,
and middleware systems on the web. It ensures that multiple
applications work simultaneously.
 With any typical web application, there are two different codes
(sub-programs) running side-by-side.
These are:
 Client-side Code - The code that is in the browser and responds to some user
input
 Server-side Code - The code that is on the server and responds to the HTTP
requests

 A web developer (team) decides as to what the code on the


server will do with respect to the code in the browser.
Client Side Development
 The client side, also known as the frontend side of the web apps is the part that
is seen and interacted by the users.

 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

 Creating dynamically changing web pages

 Letting users log in to your web app

 Letting users use their Facebook account to log in to your web app using
OAuth

 Providing a common structure to build maintainable applications

 Reading configuration files

 Serving image files

 Logging calls to your web app


An introduction to ASP.NET Core
 ASP.NET Core is the latest evolution of Microsoft’s popular ASP.NET web framework,
 released in June 2016. Recent versions of ASP.NET have seen many incremental
 updates, focusing on high developer productivity and prioritizing backwards
compatibility.
 ASP.NET Core bucks that trend by making significant architectural changes that
 rethink the way the web framework is designed and built.
 ASP.NET Core owes a lot to its ASP.NET heritage and many features have been carried
 forward from before, but ASP.NET Core is a new framework. The whole technology
 stack has been rewritten, including both the web framework and the underlying
 platform.
 At the heart of the changes is the philosophy that ASP.NET should be able to hold its
head high when measured against other modern frameworks, but that existing .NET
developers should continue to be left with a sense of familiarity.
The benefits and limitations of ASP.NET
 To understand why Microsoft decided to build a new framework, it’s important to
understand the benefits and limitations of the existing ASP.NET web framework.
 The first version of ASP.NET was released in 2002 as part of .NET Framework 1.0, in
response to the then conventional scripting environments of classic ASP and PHP.
 ASP.NET Web Forms allowed developers to rapidly create web applications using a
graphical designer and a simple event model that mirrored desktop application building
techniques.
 The ASP.NET framework allowed developers to quickly create new applications, but over
time, the web development ecosystem changed. It became apparent that ASP.NET Web
Forms suffered from many issues, especially when building larger applications.
 In particular, a lack of testability, a complex stateful model, and limited influence over the
generated HTML (making client-side development difficult) led developers to evaluate
other options.
 In response, Microsoft released the first version of ASP.NET MVC in 2009, based on the
Model-View-Controller pattern, a common web design pattern used in other frameworks
such as Ruby on Rails, Django, and Java Spring. This framework allowed you to separate UI
elements from application logic, made testing easier, and provided tighter control over
the HTML-generation process.
The benefits and limitations of ASP.NET
 ASP.NET MVC has been through four more iterations since its first release, but they have all been
built on the same underlying framework provided by the System .Web.dll file. This library is part
of .NET Framework, so it comes pre-installed with all versions of Windows. It contains all the
core code that ASP.NET uses when you build a web application.
 This dependency brings both advantages and disadvantages. On the one hand, the ASP.NET
framework is a reliable, battle-tested platform that’s a great choice for building modern
applications on Windows. It provides a wide range of features, which have seen many years in
production, and is well known by virtually all Windows web developers.
 On the other hand, this reliance is limiting—changes to the underlying System
 .Web.dll are far-reaching and, consequently, slow to roll out. This limits the extent to which
ASP.NET is free to evolve and results in release cycles only happening every few years. There’s
also an explicit coupling with the Windows web host, Internet Information Service (IIS), which
precludes its use on non-Windows platforms.
 In recent years, many web developers have started looking at cross-platform web frameworks
that can run on Windows, as well as Linux and macOS. Microsoft felt the time had come to create
a framework that was no longer tied to its Windows legacy, thus ASP.NET Core was born.
What is ASP.NET Core?
 The development of ASP.NET Core was motivated by the desire to create a web
framework with four main goals:
 To be run and developed cross-platform
 To have a modular architecture for easier maintenance
 To be developed completely as open source software
 To be applicable to current trends in web development, such as client-side
applications and deploying to cloud environments
 In order to achieve all these goals, Microsoft needed a platform that could
provide underlying libraries for creating basic objects such as lists and
dictionaries, and performing, for example, simple file operations. Up to this
point, ASP.NET development had always been focused, and dependent, on the
Windows-only .NET Framework.
 For ASP.NET Core, Microsoft created a lightweight platform that runs on
Windows, Linux, and macOS called .NET Core,
Relationship between
ASP.NET Core, ASP.NET and .NET Core
ASP.NET Core Application Model
ASP.NET Core Application Model
 The .NET Core platform provides a base console application model for
running command-line apps.
 Adding a web server library converts this into an ASP.NET Core web app.
 Additional features, such as configuration and logging, are added by way of
additional libraries.
 By adding an ASP.NET Core web server to your .NET Core app, your
application can run as a web application.
 ASP.NET Core is composed of many small libraries that you can choose from
to provide your application with different features.
 You’ll rarely need all the libraries available to you and you only add what
you need. Some of the libraries are common and will appear in virtually
every application you create, such as the ones for reading configuration files
or performing logging. Other libraries build on top of these base capabilities
to provide application-specific functionality, such as third-party logging-in
via Facebook or Google.
Advantages of ASP.NET Core
 ASP.NET Core has many selling points when compared to other cross-
platform web frameworks:
 It’s a modern, high-performance, open source web framework.
 It uses familiar design patterns and paradigms.
 C# is a great language (or you can use VB.NET or F# if you prefer).
 You can build and run on any platform.
Similarities with other Frameworks
 Many of the web frameworks available today use similar, well-established
design patterns, and ASP.NET Core is no different.
 For example,
 Ruby on Rails is known for its use of the Model-View-Controller (MVC)
pattern;
 Node.js is known for the way it processes requests using small discrete
modules (called a pipeline); and
 dependency injection is found in a wide variety of frameworks.
 If these techniques are familiar to you, you should find it easy to transfer
them across to ASP.NET Core; if they’re new to you, then you can look
forward to using industry best practices!
Programming Language C#
 The primary language of .NET development, and ASP.NET Core in particular,
is C#.
 This language has a huge following, and for good reason! As an object-
oriented C based language, it provides a sense of familiarity to those used to
C, Java, and many other languages.
 In addition, it has many powerful features, such as Language Integrated
Query (LINQ), closures, and asynchronous programming constructs.
 The C# language is also designed in the open on GitHub, as is Microsoft’s C#
compiler, codenamed Roslyn.
ASP.NET Core Performance
 TechEmpower (www.techempower.com/benchmarks) has been running
benchmarks on a whole range of web frameworks from various languages for
several years now.
 In Round 13 of the plain text benchmarks, TechEmpower announced that
ASP.NET Core with Kestrel was the fastest mainstream full-stack web
framework, in the top ten of all frameworks!
Summary

 In this Lecture we discussed Web Frameworks and Microsoft Framework


 I explained the context in which ASP.NET Core MVC exists and how it has
evolved from Web Forms and the original ASP.NET MVC Framework.
 I described the benefits of using the ASP.NET Core MVC.
 In the next lecture you’ll see ASP.NET Core MVC in action in a simple
demonstration of the features that deliver these benefits.
Thank You
ITEC 4116
Advance Web Application Development

Lecture 04

Fayyaz Muhammad
Assistant Professor

University of Education Lahore, Multan Campus


ITEC 4116
Advance Web Application Development

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

 Context in which ASP.NET Core MVC exists

 How it has evolved from Web Forms and the original ASP.NET
MVC Framework.

 Describe the benefits of using the ASP.NET Core MVC


Online Resources
 Wikipedia: https://en.wikipedia.org/wiki/World_Wide_Web
 Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/
 Java T Point: https://www.javatpoint.com/net-framework
 GeeksForGeeks: https://www.geeksforgeeks.org/net-framework-class-library-fcl/
 Tutorials Point:
https://www.tutorialspoint.com/internet_technologies/websites_development.htm
.NET Platform
 .NET is a
 free, cross-platform, open source developer platform made up of tools, programming
languages and libraries for building many different types of applications

 Purpose
 To overcome the shortcoming of previous programming technologies

 To develop a code execution environment and a code development environment

 With .NET, you can use multiple languages, editors, and libraries to build
for web, mobile, desktop, gaming, and IoT.

 Provides a run-time environment called the common language runtime


(CLR), which runs the code and provides services that make the
development process easier
.NET Framework Features
 .NET is a general purpose development platform having following
features:
 Support for Multiple Programming Languages

 Cross Platform

 Different .NET implementations


 .NET Core

 .NET Framework

 Xamarin/Mono

 Libraries

 The Programming tools


Overview of .NET Framework Components (Summary)
.NET Features Interaction
Architecture of .NET Framework
 Two major components:
 Common Language Runtime (CLR)
 Class Library
 The Common Language Runtime (CLR)
 The CLR Execution engine manages the life cycle and executes .NET applications
(code)
 To make the development proves easier. It provides services like thread
management, Memory management and garbage collection, type-safety,
exception handling, and more …
 The Class Library
 Types for strings, dates, numbers, etc. for common functionality.
 Provides a set of APIs for reading and writing files, connecting to databases,
drawing, and more and
Working of .NET
Common Language Runtime (CLR)
 CLR manages the execution of programs written in any language that uses the .NET
Framework

 Main function of CLR

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

 For desktop applications is API function called CorbindToRuntime.

 For web based applications is asp.net worker process(aspnet-wp.exe).


CLR Position
Overview of Main Components of CLR
Components of CLR
 Main components of CLR:

 Common Language Specification (CLS)

 Common Type System (CTS)

 Garbage Collection (GC)

 Just In – Time Compiler (JIT)


Common Language Specification (CLS)
 Responsible for converting the different .NET programming language
syntactical rules and regulations into CLR understandable format
 It provides the Language Interoperability.
 Language Interoperability can be achieved in two ways :
 Managed Code
 Code that's executed by the CLR (MSIL Code)

 For managed code CLR provides three .NET facilities:


 CAS (Code Access Security)
 Exception Handling
 Automatic Memory Management.
 Unmanaged Code
 It is compiled into native machine language that targets a specific system
Common Type System (CTS)
 CLS defines a subset of CTS
 CTS is a standard that specifies how type definitions and specific values of
types are represented in computer memory.
 It is intended to allow programs written in different programming
languages to easily share information.
 The CTS supports two general categories of types:
 Value Types

 Reference Types
Garbage Collector
 Provide the Automatic Memory Management feature

 How it manages memory?


Just In Time
Compiler (JIT)

Responsible for converting


the MSIL into machine code
or native code using the CLR
environment.
Class Library or Base Class Library (BCL)
 It is the sub part of the Framework that provides library support to CLR to work
properly
 It is the collection of thousands classes, namespaces, interfaces and value types
that are used for .NET applications.
 BCL supports the following functions.
 Base and user-defined data types
 Support for exceptions handling
 Input/output and stream operations
 Communications with the underlying system
 Access to data
 Ability to create Windows-based GUI applications
 Ability to create web-client and server applications
 Support for creating web services
.NET Framework Base Class Library
Categories in the Framework Class Libraries

Following are the three general


categories of Class Libraries:
1. Utility Features
2. Wrappers around OS Functionality
3. Frameworks
Summary
 Introduction to .NET
 Working of .NET
 .NET Features
 .NET Components
 Common Language Runtime (CLR)
 Components of CLR
 Class Library
Thank You
ITEC 4116
Advance Web Application Development

Lecture 05

Fayyaz Muhammad
Assistant Professor

University of Education Lahore, Multan Campus


ITEC 4116
Advance Web Application Development

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/

 Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/

 IEEE: https://spectrum.ieee.org/computing/software/the-top-programming-
languages-2019

 Tutorials Teacher: https://www.tutorialsteacher.com/csharp/csharp-tutorials

 Dot Net Tutorials: https://dotnettutorials.net/course/csharp-dot-net-tutorials/

 Tutorials Point: https://www.tutorialspoint.com/csharp/index.htm


Computer Programming
 Process of creating a program is called programming
 Commonly referred to as coding
 Purpose
 Process of designing and building an executable computer program to accomplish
a specific computing result.
 Involves tasks such as:
 Analysis
 generating algorithms
 profiling algorithms
 accuracy and resource consumption
 the implementation of algorithms in a chosen programming language
Programming Language
 A programming language is a notation or vocabulary and syntax for
writing programs to perform specific tasks
 The term programming language usually refers to high-level
languages, such as
 BASIC C
 C++ COBOL
 Java FORTRAN
 Python Pascal
 Visual Basic C#
 Two major components of each programming language:
 Unique set of keywords
 a special syntax for organizing program instructions
The Top Programming Languages 2017

Image: IEEE Spectrum Interactive Ranking (2017)


The Top Programming Languages 2018

Image: IEEE Spectrum Interactive Ranking (2018)


The Top Programming Languages 2019

Image: IEEE Spectrum Interactive Ranking (2019)


Basic Elements of any Programming Language
 Computer Programming Languages are also made of several elements
 Following are some of the common basic elements for all the programming languages
 Programming Environment
 Basic Syntax
 Data Types (Numbers, Characters, Strings)
 Variables
 Keywords
 Basic Operators
 Expressions
 Assignments
 Decision Making
 Loops
 Functions, Methods
 Data Structures
 Program
.NET and C#
 .NET is a platform to create different types of applications

 .NET supports many programming languages

 C# is an elegant and strongly typed object-oriented programming


language that enables developers to build a variety of secure and
robust applications that run on the .NET Framework.

 .NET Framework and C# makes easier to develop applications


When to use C#?
 C# is used for:
 Desktop applications
 Mobile applications
 Web applications
 Web services
 Web sites
 IoT
 Games
 VR
 Database applications
 And much, much more!
Why to Use C#?
 Few of the main reasons for using C#:
 It is one of the most popular programming language in the world

 It is easy to learn and simple to use

 It has a huge community support

 C# is an object oriented language which gives a clear structure to


programs and allows code to be reused, lowering development costs.

 As C# is close to C, C++ and Java, it makes it easy for programmers to


switch to C# or vice versa
Compile-time & run-time relationships of C# source code files, the .NET
Framework class libraries, assemblies, and the CLR
Create New Project
Create New Project …
 On the Create a new project window, enter or type console in the search box. Next, choose C# from the Language list,
and then choose Windows from the Platform list.
 After you apply the language and platform filters, choose the Console App (.NET Core) template, and then choose Next.
Configure your new project
In the Configure your new project window, type or enter HelloWorld in the Project name
box. Then, choose Create.
View your app in the console window.
Summary
 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
Thank You
ITEC 4116
Advance Web Application Development

Lecture 06

Fayyaz Muhammad
Assistant Professor

University of Education Lahore, Multan Campus


Learning Objectives
 C# Key Organizational Concepts

 Understanding the syntax and semantics of the C# programming


language

 Basic Elements of C# Programming Language

 C# Program Structure

 C# Program Components

 C# Program Working Example


Summary of the Last Lecture

 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


Online Resources
 Wikipedia: https://en.wikipedia.org/wiki/

 Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/

 Tutorials Teacher: https://www.tutorialsteacher.com/csharp/csharp-tutorials

 Dot Net Tutorials: https://dotnettutorials.net/course/csharp-dot-net-tutorials/

 Tutorials Point: https://www.tutorialspoint.com/csharp/index.htm

 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

 Programs are designed using common building blocks, known as programming


constructs.
 These programming constructs form the basis for all programs.

 Statements and Expressions are the building blocks of any program

 Actions—that a program takes are expressed in statements

 Statements are made up of keywords, expressions and operators.

 Statement—In C# a complete program instruction (action) is called a statement

 C# uses the keywords to build its programming constructs.


C# Program Syntax and Semantics
 Syntax—The form or shape of language. Syntax of a language is the order of
keywords.
 Semantics—The content or meaning of the language. Semantics is what do you
mean or what you are expressing in the code
 C# provides a variety of statements to perform various actions.
 Common actions include:
 declaring variables
 assigning values
 calling methods
 looping through collections
 branching to one or another block of code, depending on a given condition.
Flow of Control or Flow of Execution
 Statements in a program are generally executed in sequence.
 The order in which statements are executed in a program is called the flow of control or
flow of execution.
 The flow of control may vary every time that a program is run, depending on how the
program reacts to input that it receives at run time.
 There are three basic types of Flow of Control or Control Structures. All programs use
one or more of these constructs:
 Sequence is the order in which instructions occur and are processed one by
one top to bottom. This is the default flow of control.
 Selection determines which path a program takes when it is running
 Iteration is the repeated execution of a section of code when a program is
running
Elements of the C# Language
 Following topics provide an overview of the elements of the C#
language:
 Program Structure

 Types and Variables

 Expressions

 Statements

 Classes and Objects

 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

 Statements and Expressions

 Comments—Comment may also be included, it is optional, since


comments are ignored by the C# compiler.
Different Sections of a C# Program
C# Program Structure
C# Program Structure with Keywords
C# Program Structure
Summary
 C# Key Organizational Concepts

 Understanding the syntax and semantics of the C# programming


language

 Basic Elements of C# Programming Language

 C# Program Structure

 C# Program Components

 C# Program Working Example


Thank You
ITEC 4116
Advance Web Application Development

Lecture 07

Fayyaz Muhammad
Assistant Professor

University of Education Lahore, Multan Campus


Learning Objectives
 C# Character Set
 C# Programming Language General Principles
 Case Sensitivity
 Statement Termination
 Blocks
 Whitespace
 Comments
 Examples of General Principles of C# Programming Language
Summary of the Last Lecture
 C# Key Organizational Concepts

 Understanding the syntax and semantics of the C# programming


language

 Basic Elements of C# Programming Language

 C# Program Structure

 C# Program Components

 C# Program Working Example


Online Resources

 Wikipedia: https://en.wikipedia.org/wiki/

 Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/

 Tutorials Teacher: https://www.tutorialsteacher.com/csharp/csharp-tutorials

 Dot Net Tutorials: https://dotnettutorials.net/course/csharp-dot-net-tutorials/

 Tutorials Point: https://www.tutorialspoint.com/csharp/index.htm

 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

 Types and Variables

 Expressions

 Statements

 Classes and objects

 Arrays

 Interfaces

 Delegates

 Attributes
Character Set
 C# programs are written using the Unicode character set

 Unicode Character Set


C# Character Set Example
C# Basic (General) Principles
Following are the C# basic (general) principles of:

 Case Sensitivity

 Statement Termination

 Block

 Whitespace

 Comments
Case Sensitivity
C# is Case Sensitive Language
 The word “Main” is not the same as:

 its lowercase spelling, “main” or

 its uppercase spelling “MAIN” or

 any of the mixed case spelling “MaiN” or “MAiN” etc.

 They are different identifiers.


Statement Termination

 A statement can consist of a single line of code that


ends in a semicolon
C# Comments
 Comments are statements written inside our code which are just ignored by
the compiler while compiling our code

 Why Comments?
 Comments are for humans to read and not for computers

 Types of Comments

 Single Line Comments

 Multi-Line Comments

 Single Line Comments


 Start with two forward slashes (//)

 C# Multi-line Comments
 Start with /* and ends with */
C# Comments Examples
C# Whitespace
 C# is a “free format” language

 Whitespace in a program refers to characters that do not have


a visible output character
 Some of the whitespace characters include the following:
 Space
 Tab
 New line
 Carriage return

 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 execute statements conditionally

 To repeat statements

 To group statements into a method or function


C# Blocks Example
Our First C# Program
Case Sensitivity,
Statement Terminator,
Blocks,
Whitespace
and
Comments
Summary
 C# Character Set
 C# Programming Language General Principles
 Case Sensitivity
 Statement Termination
 Blocks
 Whitespace
 Comments
 Examples of General Principles of C# Programming Language
Thank You
ITEC 4116
Advance Web Application Development

Lecture 08

Fayyaz Muhammad
Assistant Professor

University of Education Lahore, Multan Campus


Learning Objectives
 Lowest Level Syntactic Elements and Structure of C#
Programming Language (Lexical Structure)
 Tokens
 Types of Tokens
 Keywords
 Identifiers
Summary of the Last Lecture
 C# Character Set
 C# Programming Language General Principles
 Case Sensitivity
 Statement Termination
 Blocks
 Whitespace
 Comments
 Examples of General Principles of C# Programming Language
Online Resources

 Wikipedia: https://en.wikipedia.org/wiki/

 Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/

 Tutorials Teacher: https://www.tutorialsteacher.com/csharp/csharp-tutorials

 Dot Net Tutorials: https://dotnettutorials.net/course/csharp-dot-net-tutorials/

 Tutorials Point: https://www.tutorialspoint.com/csharp/index.htm

 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

 Types and Variables

 Expressions

 Statements

 Classes and objects

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

 The above statement will create a variable @void of type int


Contextual Keywords
Besides regular
keywords,
C# has 25
contextual
keywords.
Contextual
keywords have
specific meaning in
a limited program
context and can be
used as identifiers
outside that
context.
They are not
reserved words in
C#.
C# Identifiers
 Each element in a C# program are given a name called identifiers.
 General rules for constructing names for unique identifiers are:

 Names can contain letters, digits and the underscore character (_)

 Names must begin with a letter

 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

University of Education Lahore, Multan Campus


Learning Objectives
 Operators
 Punctuators
 Literals
 C# Program Formation
 C# Program Working Example With Tokens
Summary of the Last Lecture
 Lowest Level Syntactic Elements and Structure of C# Programming
Language (Lexical Structure)
 Tokens
 Types of Tokens
 Keywords
 Identifiers
Online Resources

 Wikipedia: https://en.wikipedia.org/wiki/

 Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/

 Tutorials Teacher: https://www.tutorialsteacher.com/csharp/csharp-tutorials

 Dot Net Tutorials: https://dotnettutorials.net/course/csharp-dot-net-tutorials/

 Tutorials Point: https://www.tutorialspoint.com/csharp/index.htm

 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—(+, -, *, /, %)

 Relational Operators—(==, !=, <, <=, >, >=)

 Logical Operators—(And(&&), Or(||))

 Bitwise Operators—Bitwise AND (&), OR (|), Exclusive OR (^)


 Type-cast operators—is operator, as operator, cast expression, typeof operator
C# Operators…
 Types of Operators based on operands
 Operands are values, whereas operators are symbols that represent
particular actions
 There are three types of operators in C#:
 Unary operators
 Binary operators
 Ternary operators
 Unary operators—act on single operand
 Binary operators—act on two operands (left-hand side and right-hand side
operand of an operator)
 Ternary Operator—? : operates on three operands e.g.:
variable = Condition? Expression1 : Expression2;
C# Literals
 Literals are the values itself
 To know literals better, for examples:
 PI= 3.14159;
 X=5;
 In above example, 3.14159, and 5 are literals.
 Types of literals
 Integer Literals
 Floating-point Literals
 Character Literals
 String Literals
 Null Literals
 Boolean Literals
C# Punctuators
 Punctuators are used to separate different programming elements
 Types of Separators
 Space, Tab, New line (Whitespaces)
 “” (marks the String start and end)
 Semicolon(;) (Statement terminator)
 colon(:) (is the way to implement inheritance in C#)
 Comma (,) (Separator of method parameters)
 period (.) (accessor of class methods)
 parentheses ( ) (to mark the start and end of a method signature)
 Brackets [ ] (used to denote an array type)
 Braces { } (Blocks, to initialize arrays)
C# Program Formation
 In C# Program, we have comments, white spaces, keywords, Identifiers
(variables), operators, literals, and delimiters.

 Comments—It is used for Maintenance of programs.

 Whitespaces—To make program clearer and more readable

 C# programs are composed of characters from the Unicode character set.

 Characters → Tokens → Statements→ Blocks → Methods (Functions) →


Classes → Namespaces → Programs
C# Program
C# Tokens
C# Tokens with Types
Summary
 Operators
 Punctuators
 Literals
 C# Program Formation
 C# Program Working Example With Tokens
Thank You
ITEC 4116
Advance Web Application Development

Lecture 10

Fayyaz Muhammad
Assistant Professor

University of Education Lahore, Multan Campus


Learning Objectives
 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
Summary of the Last Lecture
 Tokens
 Types of Tokens
 Keywords
 Identifiers
 Operators
 Punctuators
 Literals
 C# Program Format
Online Resources

 Wikipedia: https://en.wikipedia.org/wiki/

 Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/

 Tutorials Teacher: https://www.tutorialsteacher.com/csharp/csharp-tutorials

 Dot Net Tutorials: https://dotnettutorials.net/course/csharp-dot-net-tutorials/

 Tutorials Point: https://www.tutorialspoint.com/csharp/index.htm

 tutlane: https://www.tutlane.com/tutorial/csharp/csharp-introduction

 BBC BiteSize: https://www.bbc.co.uk/bitesize/guides/zc6s4wx/revision/1


Program, Data and Types
 Program is set of instruction to perform some task
 Data
 Data is any thing that computer program uses to produce
information
 The data that is used in a program is referred to as the data values

 Computer programs manipulate (or process) data to perform some


tasks
 Type
 Data is classified into types, such as a set of whole numbers (also
known as integers) or a set of printing characters.
Data Types
 The data type of a value is an attribute that tells what kind of
data that value can have.

 A data type defines a collection of data values and a set of


predefined operations on those values.

 Computer programs use data types to organize different types


of data in a program
Variables
 Variable is a program element used to store data

 Variables act as "storage locations" for data in a program.

 Variable are a way of naming information for later usage

 Why Variables are important?

 Variables let us do dynamic things

 C# is a strongly typed language


Variables Creation (Declaration)
 To create a variable, you must specify the type and assign it a value:

 Syntax → [Data Type] [Variable Name];

[Data Type] [Variable Name] = [Value];

int billAmount=25000;

 To declare more than one variable of the same type, use a comma-

separated list:

Example int marks1, marks2, marks3;

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

 Constants are defined using the const keyword


 Syntax for defining a constant is −

 const [data_type] [constantName] = [value];

 Example const int myNumer = 15;

myNumber = 20; // error


Types of C# Data Types
 C# mainly categorized data types in two types:
 Value types
 Reference types
 The Datatypes in C# are basically used to store the data
temporarily in the computer through a program.
 Datatypes gives information about:
 Size of the memory location to hold data
 possible range of data that can be stored inside that memory location
 Possible legal operations which can be performed on that memory
location.
 Types of the results obtained from an expression when these types are
use in the expressions
Types of C# Data Types…
C# Predefined Data Types Ranges
 Following are the most common data type storage size and their values ranges:
C# Program Data Types and Variables Example
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
int number = 786;
string studentName = “Fayyaz";
double marksAverage = 78;
char gender = 'M';
bool isVerified = true;
}
}
}
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

 Types and Variables

 Expressions

 Statements

 Classes and objects

 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

University of Education Lahore, Multan Campus


Learning Objectives
 C# Program Example of Using Variables

 Namespace

 Creating Namespace

 Namespace members

 Using Keyword

 Main Method—Entry to C# Program execution

 Namespace, using and Main Method example


Summary of the Last Lecture
 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


Online Resources
 Wikipedia: https://en.wikipedia.org/wiki/

 Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/

 Tutorials Teacher: https://www.tutorialsteacher.com/csharp/csharp-tutorials

 Dot Net Tutorials: https://dotnettutorials.net/course/csharp-dot-net-tutorials/

 Tutorials Point: https://www.tutorialspoint.com/csharp/index.htm

 tutlane: https://www.tutlane.com/tutorial/csharp/csharp-introduction

 BBC BiteSize: https://www.bbc.co.uk/bitesize/guides/zc6s4wx/revision/1


Today’s Program
Today’s Program Output
Today’s Interactive Program
Today’s Interactive Program Output
Namespace
 A namespace is essentially a way to group a set of types, e.g.
classes, in a named space of its own.

 Namespaces are used:

 To organize code

 To organize too many classes so that it can be easy to handle the


larger applications

 To reduce code redundancy in larger applications

 To prevent name clashes


Defining Namespace in C#
 We can define a namespace in C# using the namespace keyword
as:

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

 For example, using System;

 Once the line: using System;

 is included at the top of the program. We can write

 Console.WriteLine("Hello World!");

 Instead of the fully qualified name i.e.

 System.Console.WriteLine("Hello World!");
Namespace Members
 A namespace can have following types as its members:

 Namespaces (Nested Namespace)

 Classes

 Interfaces

 Structures

 Delegates

 We will discuss about these topics in later lectures


Main: The Starting Point of a Program
 Every C# program must have one class with a method called Main

 The Main method is the entry point to start a C# program

 A method is a code block containing a series of statements


Namespace, using and Main Method example
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

 Types and Variables

 Expressions

 Statements

 Classes and objects

 Arrays

 Interfaces

 Delegates

 Attributes
Summary
 C# Program Example of Using Variables

 Namespace

 Creating Namespace

 Namespace members

 Using Keyword

 Main Method—Entry to C# Program execution

 Namespace, using and Main Method example


Thank You
ITEC 4116
Advance Web Application Development

Lecture 12

Fayyaz Muhammad
Assistant Professor

University of Education Lahore, Multan Campus


Learning Objectives
 Program and Statement

 Expressions

 Types of Expressions

 Program Common Actions

 Types of Statements

 Declaration Statements

 Expression Statements

 Flow Control Statements


Summary of the Last Lecture
 C# Program Example of Using Variables

 Namespace

 Creating Namespace

 Namespace members

 Using Keyword

 Main Method—Entry to C# Program execution

 Namespace, using Keyword and Main Method example


Online Resources

 Wikipedia: https://en.wikipedia.org/wiki/

 Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/

 Tutorials Teacher: https://www.tutorialsteacher.com/csharp/csharp-tutorials

 Dot Net Tutorials: https://dotnettutorials.net/course/csharp-dot-net-tutorials/

 Tutorials Point: https://www.tutorialspoint.com/csharp/index.htm

 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

 Types and Variables

 Expressions

 Statements

 Classes and objects

 Arrays

 Interfaces

 Delegates

 Attributes
Program and Statement
 Program—is a set of instruction that perform some task

 Program in C# consists of statements to perform a task

 Statement—is an action that a program takes to perform a tasks

 Statement—consists of expression, keywords and operators to


perform an action
Expressions
 An expression is a sequence of one or more operands and zero or
more operators that can be evaluated to a single value, object,
method, or namespace.
 Expressions can use operators that in turn use other expressions as
parameters, or method calls whose parameters are in turn other
method calls, so expressions can range from simple to very complex
 Examples;
 ((x < 10) && ( x > 5)) || ((x > 20) && (x < 25));

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

 string msg = "Hello World";

 Simple Name

 Simple names can be the name of a variable, type member,


method parameter, namespace or type.
 In the above example i and msg are simple name expressions
Expressions Types…
 Method Invocation

 DoWork( );

 A method invocation requires the name of the method, either as a


name as in the previous example, or as the result of another
expression, followed by parenthesis and any method parameters.

 Operator and its Operands


 The most basic expression consists of an operator, two operands and
an assignment.
 An example of an expression: int theResult = 1 + 2;
Expressions Types…
 Any unit of code that can be evaluated to a value is an expression.

 This value can be a number, a string or a logical value

 Expressions are often classified by the type of value that they represent.
For example:

 Boolean expressions : Evaluate to either TRUE or FALSE

 integer expressions: Evaluate to whole numbers, like 3 or 100

 Floating-point expressions: Evaluate to real numbers, like 3.141 or -


0.005

 String expressions: Evaluate to character strings


Program Common Actions
 A statement is a basic unit of execution of a program. A program
consists of multiple statements.
 Common actions (statements) that a program takes include:
 Declaring variables

 Assigning values

 Calling methods

 Looping through collections

 Branching to one or another block of code, depending on a given


condition
Statement Types
 Based on the action performed by a statement in a program
following are the general types of Statements in C#:

 Declaration Statements

 Expression Statements

 Control Flow Statements


Declaration Statements
➢ Declaration statements are used to declare and initialize local variables and
constants.
➢ A declaration statement introduces a new variable or constant.
➢ A variable declaration can optionally assign a value to the variable.
➢ In a constant declaration, the assignment is required.
➢ The following are examples how to declare and initialize local variables and
constants:
Local variable declaration: Local constant declaration:
static void Declarations(string[] args) static void ConstantDeclarations(string[] args)
{ {
int a; const float pi = 3.1415927f;
int b = 2, c = 3; const int r = 25;
a = 1; Console.WriteLine(pi * r * r);
Console.WriteLine(a + b + c); }
}
Expression Statements
An expression followed by a semicolon is called an
expression statement
 Expression statements are used to evaluate expressions
 Expression statements that calculate a value must store the
value in a variable
 Expressions that can be used as statements include:
 method invocations
 object allocations using the new operator
 assignments using =
 the compound assignment operators, increment and
decrement operations using the ++ and – operators
 await expressions.
Expression Statements Examples
 Expression statement examples:
 /* Assignment */
 radius=25;
 area = 3.14 * radius * radius;
 /* Method call is an expression*/
 System.Console.WriteLine("HelloWorld");
 Here, radius=25; is an expression statement
 3.14 * radius * radius is an expression and area = 3.14 * radius * radius; is
an expression statement
 Likewise,
 System.Console.WriteLine("Hello"); is both an expression and a statement
Controls Statements
 Control structures allow you to regulate the flow of your
program's execution. Control Statements—The flow of program
control is specified by control statements in C#.

 Program flow control statements can be divided into four


categories:

 Selection Statements—(if, else, switch, and case branching)

 Iteration Statements—(do, for, foreach, and while looping)

 Jump Statements—(break, continue, return, and goto statements)

 Exception Handling Statements—(try…catch, try...finally statements)


Summary
 Program and Statement

 Expressions

 Types of Expressions

 Program Common Actions

 Types of Statements

 Declaration Statements

 Expression Statements

 Flow Control Statements


Thank You
ITEC 4116
Advance Web Application Development

Lecture 13

Fayyaz Muhammad
Assistant Professor

University of Education Lahore, Multan Campus


Learning Objectives
 Flow Control Statements

 Types of Flow Control Statements

 Comparison Operators and Logical Operators

 Boolean Expressions

 If statements i.e., if-else statement

 Switch Statement

 Assemblies
Summary of Last Lecture
 Program and Statement

 Expressions

 Types of Expressions

 Program Common Actions

 Types of Statements

 Declaration Statements

 Expression Statements

 Flow Control Statements


Online Resources
 Wikipedia: https://en.wikipedia.org/wiki/

 Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/

 Tutorials Teacher: https://www.tutorialsteacher.com/csharp/csharp-tutorials

 Dot Net Tutorials: https://dotnettutorials.net/course/csharp-dot-net-tutorials/

 Tutorials Point: https://www.tutorialspoint.com/csharp/index.htm

 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

 Types and Variables

 Expressions

 Statements

 Classes and objects

 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

 Exception handling statements


 Throw, try-catch, try-finally, try-catch-finally
Comparison Operators and Boolean Expressions
 Comparison operators (Relational Operators) — operators that compare
values (pair of values) and return the result of comparison in Boolean value (true or
false).
 The operators include: >, <, >=, <=, ==, and !=
 Logical operators — operators that combine multiple Boolean expressions or
values and provide a single Boolean output (true or false)
 The operators include: &&, ||, and !
 Boolean expressions are relational comparisons between numeric expressions
resulting in a value of either True or False.
 Logical expressions are a fundamental part of control statements and are formed with
combinations of two kinds of operators:
 Relational operators—which relate two expressions of compatible types
 Logical operators—which operate on logical operands
Comparison Operators and Boolean Expressions Examples
 Comparison Operators Logical operators compare two Boolean expressions
Operator Action Operator Meaning
== Equal to && (AND) true if both expressions are true
!= Not equal to
|| (OR) true if one expression is true
> Greater than
! (NOT) Makes true expressions false and
>= Greater than or equal to
< Less than false expressions true
<= Less than or equal to

• The expression "5 > 3" is evaluated as true.


• The expression "3 > 5" is evaluated as false.
• "5>=3" and "3<=5" are equivalent Boolean expressions, both of which are evaluated as true
• bool result = (2 < 3) && (3 < 4);
• bool result = (2 < 3) || (1 == 2);
Decision Making
This is the general form of a
typical decision making structure
found in most of the programming
languages −An if statement
identifies which statement to run
based on the value of a Boolean
expression.
It causes the program control to
be transferred to a specific flow
based upon the certain condition
is true or not.
Selection Statements
 Selection statements are used to select one of a number of possible statements
for execution based on the value of some expression.
 C# contains the if and switch selection statements.
 if statement:
 If statement is used to check whether the condition is true or false. If condition is
true, performs a function or executes the statements in the if block.
 if Else statement:
 If else statement is defined as two conditions if and else. It checks the two conditions
if and else. When the if condition is true it executes the statements of if condition,
When the if condition is false it executes the statements in to the else condition block
 Switch statement:
 Switch statement consists of more sections, each section consists of case labels.
switch statements results cleaner code than multiple if statements
If else Statements (Conditionals)
If Statements
An if statement in C# can take two forms, as the following example shows.
// if statement without an else
if (condition)
{
then-statement;
}
// Next statement in the program.

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

bool condition = true;


if (condition)
{
Console.WriteLine("The variable is set to true.");
}
else
{
Console.WriteLine("The variable is set to false.");
}
Switch Statement
 Switch is a selection statement that chooses a single switch section to execute
from a list of candidates based on a pattern match with the match expression.

 A switch statement includes one or more switch sections.

 Each switch section contains one or more case labels (either a case or default
label) followed by one or more statements.

 However, no two case labels may contain the same expression.

 switch statement is often used as an alternative to an if-else construct if a


single expression is tested against three or more conditions

 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

 When source code is compiled, a file that is automatically generated by the


compiler of every .NET application is called an assembly.

 The generated file can be either an executable files (.exe) or Dynamic Link
Library (.dll)

 It is generated only once for an application and upon each subsequent


compilation the assembly gets updated.

 When the program needs to be executed, this assembly (MSIL or


intermediate code) is converted to binary executable code, called native code
Assemblies …
 A .NET static assembly can consist of following elements:

 Assembly Manifest – Information about the current version of the assembly,


assembly name, strong key name, references to other assembly, and other related
information

 Type Metadata – Defines all types, their properties and methods

 MSIL – Microsoft intermediate language


 An Assembly contains Intermediate Language (IL) code, which is similar to Java byte code. In
the .NET language, it consists of metadata. Metadata enumerates the features of every “type”
inside the assembly or the binary.

 A set of Resources – All other resources like icons, images etc.


Summary
 Flow Control Statements

 Types of Flow Control Statements

 Comparison Operators and Logical Operators

 Boolean Expressions

 If statements i.e., if-else statement

 Switch Statement

 Assemblies
Thank You
ITEC 4116
Advance Web Application Development

Lecture 14

Fayyaz Muhammad
Assistant Professor

University of Education Lahore, Multan Campus


Learning Objectives
 Flow Control Statements

 Iteration statements

 for statement

 while statement

 do—while statement

 foreach—in statement
Summary of Last Lecture
 Flow Control Statements

 Types of Flow Control Statements

 Comparison Operators and Logical Operators

 Boolean Expressions

 If statements i.e., if-else statement

 Switch statement

 Assemblies
Online Resources
 Wikipedia: https://en.wikipedia.org/wiki/

 Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/

 Tutorials Teacher: https://www.tutorialsteacher.com/csharp/csharp-tutorials

 Dot Net Tutorials: https://dotnettutorials.net/course/csharp-dot-net-tutorials/

 Tutorials Point: https://www.tutorialspoint.com/csharp/index.htm

 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

 Exception handling statements


 Throw, try-catch, try-finally, try-catch-finally
Iteration statements
 Repeated execution of a statement or set of statements is called iteration.

 Programming languages provide loops

 Loop statements or Iteration statements are used to repeat statements that


you want executed more than once.

 C# provides following iteration statements that cause statements (or block of


statements) to be executed zero or more times, subject to some loop-
termination criteria
 for statement

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

 At any point within the for statement block:


 break out of the loop by using the break statement, or

 step to the next iteration in the loop by using the continue


statement

 Exit a for loop—the goto, return, or throw statements

 The for keyword indicates a loop in C#


Flow of for Loop

Retrieved from the source: Tutorial Points


https://www.tutorialspoint.com/csharp/csharp_loops.htm
Structure of the for statement
 The for statement defines initializer, condition, and iterator sections:
for (initializer; condition; iterator)
body
 All three sections are optional.
 The body of the loop is either a statement or a block of statements.
 The initializer section—The statements in the initializer section are executed
only once, before entering the loop. We declare and initialize a local loop variable,
which can't be accessed from outside the loop but generally used in conditional
expression and steps part
 The condition section—This section, if present, must be a Boolean expression.
That expression is evaluated before every loop iteration. If the condition section is
not present or the Boolean expression evaluates to true, the next loop iteration is
executed; otherwise, the loop is exited.
 The iterator section—defines what happens after each iteration of the body of
the loop. This section contains zero or more statement expressions, separated by
commas
for Loop Example

Retrieved from source: TutorialTeacher.com with thanks


while Loop
 while statement—executes a statement or a block of statements
while a specified Boolean expression evaluates to true.
 Expression is evaluated before each execution of the loop, a
while loop executes zero or more times
 break statement is used to breakout of the loop at any point
within the while statement block
 continue statement is used to step directly to the evaluation of
the while expression. If the expression evaluates to true,
execution continues at the first statement in the loop.
Otherwise, execution continues at the first statement after the
loop
 Exit a while loop—the goto, return, or throw statements
Flow of while loop
The syntax of a while loop in
C# is −

while( condition )
{
statement(s);
}

//while Statment Example


int n = 0;
while (n < 5)
{
Console.WriteLine(n);
n++;
}
do Loop (do—while)
 do statement—executes a statement or a block of statements while a
specified Boolean expression evaluates to true.
 Because that expression is evaluated after each execution of the loop, a
do-while loop executes one or more times. This differs from the while
loop, which executes zero or more times.
 break statement is used to break out of the loop at any point within the
do statement block
 continue statement is used to step directly to the evaluation of the
while expression. If the expression evaluates to true, execution
continues at the first statement in the loop. Otherwise, execution
continues at the first statement after the loop.
 Exit a while loop—the goto, return, or throw statements
do—while Loop
The syntax of a do...while loop in C# is:
do
{
statement(s);
} while( condition );
//do—while Statment Example
int n = 0;
do
{
Console.WriteLine(n);
n++;
} while (n < 5);
foreach loop
 foreach statement—executes a statement or a block of statements for
each element in an array or an object collection

 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

 break statement—break out of the loop.

 continue statement—to go to the next iteration in the loop

 Exit a foreach loop—the goto, return, or throw statements


How foreach loop works?
Syntax of foreach loop

foreach (element in iterable-item)


{
// body of foreach loop
}
Source: https://www.programiz.com/csharp-
programming/foreach-loop
When to use?
Following looping statements are used in c# as iteration
statement
➢ for
➢ while
➢ do—while
➢ foreach—in
But when to use each of the above?
Summary
 Flow Control Statements

 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

University of Education Lahore, Multan Campus


Learning Objectives
 Class

 Objects

 Members

 Access Modifiers

 Dot (.) Operator

 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/

 Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/

 Tutorials Teacher: https://www.tutorialsteacher.com/csharp/csharp-tutorials

 Dot Net Tutorials: https://dotnettutorials.net/course/csharp-dot-net-tutorials/

 Tutorials Point: https://www.tutorialspoint.com/csharp/index.htm

 Tutlane: https://www.tutlane.com/tutorial/csharp/csharp-introduction

 GeeksForGeeks: https://www.geeksforgeeks.org/c-sharp-class-and-object/

 Complete C# Tutorial: https://www.completecsharptutorial.com/basic/class.php


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

 Types and Variables

 Expressions

 Statements

 Classes and objects

 Arrays

 Interfaces

 Delegates

 Attributes
C# Class
 Class—basic building block of object-oriented programming

 Class—template, declaration or blueprint that is used for classifying the


object

 Classes are the most fundamental of C#’s types

 A class enables you to create your custom types by grouping variables


of other types, methods, and events

 A class is a data structure that combines state (fields) and actions


(methods and other function members) in a single unit

 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...
}

The class keyword is preceded by the access level.


Class Declaration
In general, class declarations can include these in order:

 Modifiers: A class can be public or internal etc. By default modifier of class


is internal.

 Keyword class: A class keyword is used to declare the type class.


 Class Identifier: The variable of type class is provided. The identifier(or
name of class) should begin with a initial letter which should be capitalized
by convention.
 Base class or Super class: The name of the class’s parent (superclass), if
any, preceded by the : (colon). This is optional.
 Body: The class body is surrounded by { } (curly braces)
 There can be some optional attributes that can be used with class
declaration according to the application requirement
Source: https://www.geeksforgeeks.org/c-sharp-class-and-object/
Class Declaration

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)

 An object is basically a block of memory that has been allocated and


configured according to the blueprint (class)

 A program may create many objects of the same class.

 Objects—also called instances to access the defined properties (data) and


methods (functionality)

 Objects—stored in either a named variable or in an array or collection


 Objects—created by using the new keyword followed by the name of the
class that the object will be based on, like this:
Customer object1 = new Customer();
Members
Classes have members that represent their data and behavior
 Behavior and data of a class are defined in the class body

 A class may contain following kinds of members:


 Fields
 Constants
 Properties
 Methods
 Events
 Constructors
 Operators
 Indexers
Members Description
Description of few of the kinds of members are as follows:
 Fields—are variables declared at class scope. A field may be a built-in
numeric type or an instance of another class.
 Constants–are fields whose value is set at compile time and cannot be
changed
 Properties—are methods on a class that are accessed as if they were
fields on that class. A property can provide protection for a class field to
keep it from being changed without the knowledge of the object.
 Methods—define the actions that a class can perform. Methods can take
parameters that provide input data, and can return output data through
parameters. Methods can also return a value directly, without using a
parameter. For example Main Method
 Event—provide notifications about occurrences, such as button clicks or
the successful completion of a method, to other objects
 Constructors—methods that are called when the object is first created
and often used to initialize the data of an object
Access Modifiers
 All types and type members have an accessibility level
 Accessibility level controls whether they can be used from other code in
an assembly or other assemblies.
 Access modifiers are applied to the declaration of the class, method,
properties, fields, and other members
 Access modifiers to specify the accessibility of a type or member are:
 public
 private
 protected
 internal
 protected internal
 private protected
Access Modifiers Description
Following are the description of each of access modifiers for type or
member:
 public—accessed by any other code in the same assembly or another
assembly that references it
 private—accessed only by code in the same class
 protected—accessed only by code in the same class, or in a class that is
derived from that class
 internal—accessed by any code in the same assembly, but not from
another assembly
 protected internal—accessed by any code in the assembly in which it's
declared, or from within a derived class in another assembly
 private protected—accessed only within its declaring assembly, by
code in the same class or in a type that is derived from that class
The Dot (.) Operator
 To access the namespace members or type (class) members, the dot
(.) operator is used

 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( )

 where Console is the class and WriteLine is the method and

 to restrict the class name to a specific namespace (in this case to


locate Console within the System namespace)

System.Console.WriteLine( )
C# - Arrays
 A variable can hold only one literal value e.g. int x = 100;

 If you want to store multiple literal values?

 Array is a data structure that stores fixed number of literal values


of the same data type and fixed number of literal values
(variables) are accessed through computed indices.

 The variables contained in an array, also called the elements of the


array, are all of the same type, and this type is called the element
type of the array

 The indices of the elements of an array range from 0 to Length - 1.


C# - Arrays Declaration
 An array is declared in the same way as variable, but with the
square brackets [ ].
 The following declares arrays of different types:
 int[] marks; // stores integer values
 string[] names; // stores string values
 double[] salaries; // stores double values
 Teacher[] teachers; // stores objects of the Teacher class

 An array stores the fixed number of elements


 To insert values to it, we must create an object of an array.
 The following creates an array of the int type:
 int[] marks = new int[5];
C# - Arrays Example
using System;
class ArrayExample
{
static void Main( )
{
int[] a = new int[10];
for (int i = 0; i < a.Length; i++)
{
a[i] = i * i;
}
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine($"a[{i}] = {a[i]}");
}
}
}
C# Collections
 In C#, collection is a class that represents group of objects

 Collections facilitates to perform following operations on objects such as

 store object

 update object

 delete object

 retrieve object

 search object, and

 sort object

 In short, all the data structure work can be performed by C#


collections
C# Collections
 Two ways to create and mange group of related objects:
 by creating arrays of objects
 Array has size limit and are most useful for creating and working with a
fixed number of strongly-typed objects
 by creating collections of objects
 Objects stored in collection can grow or shrink dynamically

 Collections provide a more flexible way to work with groups of objects.


For some collections, you can assign a key to any object that you put into
the collection so that you can quickly retrieve the object by using the key

 A collection is a class, so you must declare an instance of the


class before you can add elements to that collection.
C# Collections Example
// Create a list of strings.
var provinces = new List<string>( );
provinces.Add(“Punjab");
provinces.Add(“KPK");
provinces.Add(“Baluchistan");
provinces.Add(“Sindh");
// Iterate through the list.
foreach (var province in provinces)
{
Console.Write(province + " ");
}
// Output: Punjab KPK Baluchistan Sindh
Summary
 Class

 Objects

 Members

 Access Modifiers

 Dot (.) Operator

 Arrays

 Collections
Thank You
ITEC 4116
Advance Web Application Development

Lecture 16

Fayyaz Muhammad
Assistant Professor

University of Education Lahore, Multan Campus


Learning Objectives
 Characteristics of Modern Web Applications

 ASP.NET Core MVC

 Approaches to Building Web Applications

 When to use Traditional Web Applications?

 When to use Single Page Applications?

 First ASP.NET Core MVC Application


Summary of Last Lecture
 Class

 Members

 Access Modifiers

 Dot (.) Operator

 Arrays

 Collections
Online Resources
 Wikipedia: https://en.wikipedia.org/wiki/

 Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/core/

 Tutorials Teacher: https://www.tutorialsteacher.com/core

 Dot Net Tutorials: https://dotnettutorials.net/course/asp-net-core-tutorials/

 Tutorials Point: https://www.tutorialspoint.com/asp.net_core/index.htm

 Yogi Hosting: https://www.yogihosting.com/aspnet-core-introduction/

 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

 To be available 24/7/365 from anywhere in the world

 Usable from virtually any device or screen size

 Accessible from large number of users concurrently

 Must be secure, flexible, and scalable to meet spikes in demand

 Increasingly, complex scenarios should be handled by rich user


experiences built on the client using JavaScript and communicating
efficiently through web APIs.
ASP.NET Core MVC
 A rich framework for building web apps and APIs using the Model-View-
Controller design pattern that enable a clean separation of concerns.

 Optimized for modern web applications and cloud-based hosting scenarios

(public cloud, private cloud, any cloud)

 Modular in design—enables applications to depend on only those features they


actually use, improving application security and performance while reducing
hosting resource requirements

 Higher-throughput—can serve more customers from an application given the


same hardware, further reducing the need to invest in servers and hosting
infrastructure

 Traditional and SPA behaviors supported


Approaches to Building Web Applications
 Two general approaches to building web applications today:

1. Traditional web applications—perform most of the application


logic on the server

2. Single page applications (SPAs)—perform most of the user


interface logic in a web browser, communicating with the web server
primarily using web APIs.

3. A hybrid approach is also possible

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

 Frequent web request calls impacting the performance of the website

 Use traditional web applications when:

 Application’s client-side requirements are simple or even read-only

 Application needs to function in browsers without JavaScript support

 Team is unfamiliar with JavaScript or TypeScript development techniques


When to use Single Page Applications (SPA)?
 In SPA development style, modern front-end frameworks provides all the
necessary tools to perform interactive UI logic at client side and make only
necessary calls to the server side

 Reduced server requests and improves performance

 Use a SPA when:


 Application must expose a rich user interface with many features

 Team is familiar with JavaScript and/or TypeScript development

 Application must already expose an API for other (internal or public) clients

 SPA frameworks require greater architectural and security expertise

 Improvements in user experience made possible by the SPA model must be


weighed against these considerations
First ASP.NET Core MVC Application
Summary
 Characteristics of Modern Web Applications

 ASP.NET Core MVC

 Approaches to Building Web Applications

 When to use Traditional Web Applications?

 When to use Single Page Applications?

 First ASP.NET Core MVC Application


Thank You
ITEC 4116
Advance Web Application Development

Lecture 17

Fayyaz Muhammad
Assistant Professor

University of Education Lahore, Multan Campus


Learning Objectives
 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
Summary of Last Lecture
 Characteristics of Modern Web Applications

 ASP.NET Core MVC Framework

 Approaches to Building Web Applications

 When to use Traditional Web Applications?

 When to use Single Page Applications?

 First ASP.NET Core MVC Application


Online Resources
 Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/core/

 Tutorials Teacher: https://www.tutorialsteacher.com/core

 Dot Net Tutorials: https://dotnettutorials.net/course/asp-net-core-tutorials/

 Tutorials Point: https://www.tutorialspoint.com/asp.net_core/index.htm

 Yogi Hosting: https://www.yogihosting.com/aspnet-core-introduction/

 DotNetTricks: https://www.dotnettricks.com/learn/aspnetcore

 CodeMaze: https://code-maze.com/getting-started-with-asp-net-core-mvc/

 Complete C# Tutorial: https://www.completecsharptutorial.com/aspnet-tutorial-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

 Solutions—a container for one or more projects that make up a


particular application along with build information
 Text file (extension .sln) having its own unique format and not intended to be
edited by hand

 Contains only projects

 Cannot be nested

 Projects can belong to multiple solutions

 Only one solution open at a time in a particular instance of VS2019


Project
 Projects—Two main jobs:
 Act as a container for our source files
 Compile those files into some kind of component (assembly), typically either DLL
or EXE
 Projects—hold the items needed to build your app such as:
 Source code files, bitmaps, icons, and component and service references
 Compiler settings and other configuration files needed by various services that
project communicates with
 Default location for every new project is at:
%USERPROFILE%\source\repos
 Default location can be changed from:
Tools > Options > Projects and Solutions > Locations
 Even if an empty project is created VS2019 generates several new files
Templates
 Template—predefined structure or framework
and code to quickly and easily start a project
 Lot of templates installed with VS2019

 Types

 Project Template—new project creation

 Item Templates—Add New item window

 Installed, developed and downloaded developed by


community
Project Templates
 ASP.NET Core Web Application

 Empty

 Web Application (Model-View-Controller)

 API

 Web Application

 Angular, React.js, React.js and Redux


Item Templates
 Predefine Item Templates include:

 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

University of Education Lahore, Multan Campus


Learning Objectives
 Overview of ASP.NET Core Application

 ASP.NET Core Project Structure Description

 A Data Entry Application using ASP.NET Core MVC Demo


Summary of Last Lecture
 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


Online Resources
 Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/core/

 Tutorials Teacher: https://www.tutorialsteacher.com/core

 Dot Net Tutorials: https://dotnettutorials.net/course/asp-net-core-tutorials/

 Tutorials Point: https://www.tutorialspoint.com/asp.net_core/index.htm

 Yogi Hosting: https://www.yogihosting.com/aspnet-core-introduction/

 DotNetTricks: https://www.dotnettricks.com/learn/aspnetcore

 CodeMaze: https://code-maze.com/getting-started-with-asp-net-core-mvc/

 Complete C# Tutorial: https://www.completecsharptutorial.com/aspnet-tutorial-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)

 Dependencies—all the reference of the NuGet packages, dotnet


core runtime and asp.net core runtime libraries.

 Properties—contains a launchSettings.json file containing


configuration details about what action to perform when the
application is executed and contain details like

 IIS settings, application URLs, authentication, SSL port details, etc


Project Files and Folders Description…
 wwwroot—Folder that contains sub-folder to categories all
the static files (HTML, CSS, js, images etc) required by the
project and served to users
 CSS files—CSS folder

 javascript files—js folder

 External libraries like bootstrap, jquery— library folder


Project Files and Folders Description…
 The Models, Views, and Controllers—Folders to contain the files
that supports the components of the Model-View-Controller (MVC)
architecture (pattern)

 Controllers—handles all the incoming requests


 All the controllers needed for the project are stored here

 Models—represents the data of the application and a ViewModel


represent data that will be displayed in the UI
Project Files and Folders Description…
 Views—represent the user interface that displays Model or ViewModel
data
 View—provide an option to let the user modify Model or ViewModel
data
 Views related to a controller are stored in a folder with the name of
controller e.g.; HomeController related views—stored in Home folder
under view folder

 All the shared views across the application are kept in


Shared folder
Project Files and Folders Description…
 appsettings.json—file contains configuration settings how
ASP.NET Core App will load on startup e.g.; database connection
strings or other things that you don't want to hard-code
Project Files and Folders Description…
 Program.cs—Entry point of Web Application
 Program.cs—used to initiate, build, run the server (IIS and
Kestrel) and host the application and finalize the configuration of
the application using Startup.cs class
 Code for the program class is automatically generated
 ASP.NET Core web application is actually a console project
 Console App—start executing from the entry point that is
 public static void Main ( ) in Program class

 In Main method—create the infrastructure of the app like host


(web server) and ASP.Net Core pipeline for the web app
Project Files and Folders Description…
 Startup.cs—Two primary functions –configure the services for
dependency injection and request pipeline which handles all HTTP
requests made to the web app
 Startup.cs—Two methods:
 ConfigureServices
 Optional—if it exists, then it is the first method invoked by the WebHost
 Configure the services and Add the services in the DI Container
 Configure
 Mandatory—invoked after the ConfigureServices method
 Configure the ASP.NET Core request pipeline
 Middleware—Components that make up the request pipeline
 Middleware—handles and modifies incoming HTTP requests, and serves things like
static content or error pages etc.
A Data Entry Application using ASP.NET Core MVC
 Goal is to demonstrate ASP.NET Core in action
 Imagine that a friend has decided to host a New Year’s Eve party and that
he has asked you to create a web app that allows his invitees to
electronically RSVP ("Please respond" to require confirmation of an
invitation). He has asked for these key features:
 A home page that shows information about the party

 A form that can be used to RSVP

 A summary page that shows who is coming to the party

 Create an ASP.NET Core project and use it to create a simple application


that contains these features

Source: Pro ASP.Net Core MVC 2, Adam Freeman, 7th Edition 2017, Apress
Summary
 Overview of ASP.NET Core Application

 ASP.NET Core Project Structure

 A Data Entry Application using ASP.NET Core MVC Demo


Thank You
ITEC 4116
Advance Web Application Development

Lecture 19

Fayyaz Muhammad
Assistant Professor

University of Education Lahore, Multan Campus


Learning Objectives
 Model View Controller (MVC) Pattern

 Separation of Concern (SoC)

 User Interaction in MVC

 Understanding Models

 Understanding Views

 Understanding Controllers

 Creating Model, View and Controller and Their Interaction


Demo Application
Summary of Last Lecture
 Overview of ASP.NET Core Application

 ASP.NET Core Project Structure Description

 A Data Entry Application using ASP.NET Core MVC Demo


Online Resources
 Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/core/

 Tutorials Teacher: https://www.tutorialsteacher.com/core

 Dot Net Tutorials: https://dotnettutorials.net/course/asp-net-core-tutorials/

 Tutorials Point: https://www.tutorialspoint.com/asp.net_core/index.htm

 Yogi Hosting: https://www.yogihosting.com/aspnet-core-introduction/

 DotNetTricks: https://www.dotnettricks.com/learn/aspnetcore

 CodeMaze: https://code-maze.com/getting-started-with-asp-net-core-mvc/

 Complete C# Tutorial: https://www.completecsharptutorial.com/aspnet-tutorial-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

 MVC—divides the related program logic into three interconnected


elements
 MVC—Traditionally used for desktop GUIs and is in use since late
1970s

 MVC—Now popular for designing web applications


MVC Design Pattern Components
 Three components make up the MVC design pattern:
 Model—Central component of the pattern
 Application's dynamic data structure, independent of the user
interface
 Directly manages the data, logic and rules of the application

 Receives user input from the controller

 View—presentation of the model in a particular format


 Template that displays the data provided by the model as a user
interface
 Controller—Accepts input, optionally validates it and converts it to
commands for the model or view
Separation of Concerns (SoC)
 SoC—design principle for separating a computer program into distinct
sections that addresses a separate concern

 Concern—set of information that affects the code of a program

 SoC—states that each component of the application is responsible for


only one thing and do not depend upon any other component as much as
possible mean loosely coupled

 SoC—makes application easily testable, maintainable and extensible


 MVC—follows the SoC Philosophy
Advantages of MVC
 Popular programming languages like
 JavaScript, Python, Ruby, PHP, Java and Swift have MVC frameworks –for web or
mobile application development

 Web Apps need combining several technologies e.g., databases, HTML, and
executable code usually split into a set of tiers or layers

 Similarly ASP.NET Core framework uses MVC to separate:


 Logic that manipulates data is in Model

 Logic that display data is in the view

 Logic that handles user requests and input is contained only in controllers

 Easily testable, maintainable and extensible Web Apps and APIs


Working in an MVC Application
A different
component
handles each
aspect of the
request.

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

 The model should not


 Expose details of how the model data is obtained or managed (details
of the data storage mechanism should not be exposed to controllers
and views)
 Contain logic that transforms the model based on user interaction
(controller’s job)
 Contain logic for displaying data to the user (view’s job)
Understanding Models…
 Banking application—accounts, the general ledger, and credit limits for
customers
 Operations—depositing funds and making withdrawals from the accounts.
 Preserving the state and consistency of the data—making sure that all
transactions are added to the ledger and that a client doesn’t withdraw more
money than he is entitled to or more money than the bank has.
 Model is a class or collection of C# classes public class Student
{
 Model class holds data in public
public int StudentId { get; set; }
properties public string StudentName { get; set; }

 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

 Should not contain logic that


 manages the appearance of data (job of the view)
 manages the persistence of data (job of the model)
Understanding Controllers…
 In ASP.NET MVC
 Controller is used to define and group a set of actions
also called action methods—that handles incoming
requests
 Every controller class name must end with a word
"Controller“, for example:
Controller for home page must be HomeController and
controller for student must be StudentController
 Every controller class must be located in Controller
folder of MVC folder structure
Controller and Action Method Example

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

 Separation of Concern (SoC)

 User Interaction in MVC

 Understanding Models

 Understanding Views

 Understanding Controllers

 Creating Model, View and Controller and Their Interaction


Demo Application
Thank You
ITEC 4116
Advance Web Application Development

Lecture 20

Fayyaz Muhammad
Assistant Professor

University of Education Lahore, Multan Campus


Learning Objectives
 Action Method

 Action Selector

 Action Verbs

 Action Results

 Action Filters

 Razor View Engine

 Razor Syntax

 View Types and Discovery

 A Demo Application Describing the Razor Syntax and Strongly Typed Views
Summary of Last Lecture
 Model View Controller (MVC) Pattern

 Separation of Concern (SoC)

 User Interaction in MVC

 Understanding Models

 Understanding Views

 Understanding Controllers

 Creating Model, View and Controller and Their Interaction


Demo Application
Online Resources
 Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/core/

 Tutorials Teacher: https://www.tutorialsteacher.com/core

 Dot Net Tutorials: https://dotnettutorials.net/course/asp-net-core-tutorials/

 Tutorials Point: https://www.tutorialspoint.com/asp.net_core/index.htm

 Yogi Hosting: https://www.yogihosting.com/aspnet-core-introduction/

 DotNetTricks: https://www.dotnettricks.com/learn/aspnetcore

 CodeMaze: https://code-maze.com/getting-started-with-asp-net-core-mvc/

 Complete C# Tutorial: https://www.completecsharptutorial.com/aspnet-tutorial-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

 Execute the appropriate business logic corresponding to the


incoming request
 Choose the appropriate kind of response to return
Action Method…
 Action Methods—like any other normal methods with the
following restrictions:
 must be public. It cannot be private or protected
 cannot be overloaded
 cannot be a static method
 returns ActionResult—base class of all the result types
 Action method—doesn’t generate a response directly but chooses what
sort of response to send and prepares the data for it by calling appropriate
service in the application model to handle request e.g.;
 returning a ViewResult doesn’t generate any HTML at that point it
indicates which view template to use and the view model it will have
access to
 ViewResult—generates an HTML response using Razor (by default)
Action Selectors
 Action selector—attribute that can be applied to the action methods.
 Helps routing engine to select the correct action method to invoke to
handle a particular request
 Following are the action selector attributes:

 ActionName—allows to specify a different action name than the method name

 NonAction—indicates that a public method of a controller is not an action


method that cannot be invoked by URL but used for reusable operations in a
controller

 ActionVerbs—selects an action method based on HTTP request methods (what


kind of http request the action method support) E.g. POST, GET, PUT etc.
Action Verbs
 Action methods cannot overload as C# methods but Action Verbs
help to overload action methods
 Action Verbs— Allow to define two different action methods with the same name
but one responds to an HTTP Get request and another responds to an HTTP Post
request
 E.g. Edit method. One Edit method responds to a Get Request and renders the Edit
Form. The other method responds to the Post request and updates the database
 ASP.NET framework supports different Action Verbs, such as:
 HttpGet, HttpPost, HttpPut, HttpDelete, HttpOptions & HttpPatch
 If you do not apply any attribute then it considers it a GET request by default
 Most Common Action Verbs usage:
 GET—To retrieve the information from the server
 POST—To create a new resource
 PUT—To update an existing resource
 DELETE—To delete an existing resource
ActionName Example

public class StudentController : Controller In this example,


{ • ActioName("find") attribute is
public StudentController( ) applied to GetById action method.
{}
• So now, action name is "find" instead
[ActionName("find")] of "GetById".
public ActionResult GetById(int id) • This action method will be invoked
{ on http://localhost/student/find/1
// get student from the database request instead of
return View();
} http://localhost/student/getbyid/1
} request.
Action Result
 Action Result—actually a data type
 Action Result—becomes a return type when it is used with action
method of a controller
 Action Result—an abstract base class of all the result types (classes)
which returns from action method which implements IActionResult
 Action Result—has many derived classes
 Action methods—return models to views, file streams, redirect to
other controllers, or whatever is necessary for the task at hand
Action Result Types
 ASP.NET Core has many different types of IActionResult:
 ViewResult

 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

 Custom filters can be created to handle cross-cutting concerns


 Examples of cross-cutting concerns include: Error Handling,
Caching, Configuration, Authorization and Logging
 Filters—avoid duplicating code
Filter types
 ASP.NET MVC framework supports the following type of filters that
is executed at a different stage in the filter pipeline:
 Authorization filters—run first and are used to determine
whether the user is authorized for the request
 Resource filters—Run after authorization
 OnResourceExecuting runs code before the rest of the filter
pipeline
 OnResourceExecuted runs code after the rest of the pipeline has
completed
 Action filters—Run code immediately before and after an action
method is called
 Can change the arguments passed into an action
 Can change the result returned from the action
Filter types…
 Exception filters—apply global policies to unhandled exceptions
that occur before the response body has been written to

 Result filters—run code immediately before and after the


execution of action results

 run only when the action method has executed successfully and

useful to modify a view result right before the view is rendered


to the browser
Filter Scopes
 Filters can be scoped at three different levels:
 Particular action as an attribute

 All actions within a controller with attribute

 Register a filter globally, to be run with every MVC action

(ConfigureServices method in Startup)


What is Razor?
 Web Apps—ability to dynamically generate contents
 View Engine—responsible for producing an HTML response
 when controller action methods invokes the View( ) or PartialView( ), it
invokes view engine that produces the HTML Response
 Razor View Engine
 one of the supported and default view engine for the ASP.NET Core apps
 looks for Razor markup in the view file and parses it and produces the
HTML response by incorporating data into HTML documents
 allows to write mix of HTML and server side code using C# to perform
logical tasks in the view page like expression creation, conditional
statements, loops and variables in the view page
 C# code create dynamic web content on the fly by executing on the server
while a web page is written to the browser
What is Razor Syntax?
 Razor Syntax—not a programming language
 consists of Razor markup (syntax and Keywords), C#, and HTML to
generate view
 a server side markup language or syntax that allows to embed server-
based code (C#) into web pages or to insert C# code inside HTML
Markup
 based on the ASP.NET framework, the part of the .NET Framework
that's specifically designed for creating web applications.
 uses its own syntax and keywords to generate view

 Files containing Razor generally have a .cshtml file extension.


 Razor expressions can contain almost any C# statement—hard to decide
whether logic should belong in the view or in the controller, which can
erode the SoC philosophy
Razor Code
 Razor Syntax
 uses the @ symbol to transition from HTML markup to the C#
code
 @ symbol is used to start single line expression, single
statement block or multi-statement block
 Two ways to achieve the transitions from HTML to C#
 Using Razor code expressions
 Using Razor code blocks
 These expressions are evaluated by the Razor View Engine and
written to the response
Razor Code Expressions
 Razor Code Expressions—start with @ and followed by C# code
 The Code expression can be either Implicit or Explicit

 Implicit Razor Expressions—start with @ followed by C# code

 Explicit Razor Expressions—start with @ followed by ( ).


 Any content within the ( ) parenthesis is evaluated and rendered to

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

 E.g. @model PartyInvites.Models.Guest


 This is the very first line in the page, and it serves to define the model with which the view
will be working

 Here model is in the PartyInvites.Models namespace and is an object of type Guest

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

 Code is added to a page using the @ character

 You can enclose code blocks in braces

 Inside a block, you end each code statement with a semicolon

 You can use variables to store values

 You enclose literal string values in double quotation marks

 You can write code that makes decisions and repeat (loop)

 You can intermingle code and HTML code


Demo
 In today’s demo we will cover following:
 Strongly Typed Views
 @model and @Model
 Razor Syntax
 Variable Declaration
 If Conditionals
 Foreach Statement
 View Discovery
Summary
 Action Method
 Action Selector
 Action Verbs
 Action Results
 Action Filters
 Razor View Engine
 Razor Syntax
 View Types and Discovery
 A Demo Application Describing the Razor Syntax and Strongly
Typed Views
Thank You
ITEC 4116
Advance Web Application Development

Lecture 21

Fayyaz Muhammad
Assistant Professor

University of Education Lahore, Multan Campus


Learning Objectives
 Routing

 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 View Engine

 Razor Syntax

 View Types and Discovery

 A Demo Application Describing the Razor Syntax and Strongly Typed


Views
Online Resources
 Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/core/

 Tutorials Teacher: https://www.tutorialsteacher.com/core

 Dot Net Tutorials: https://dotnettutorials.net/course/asp-net-core-tutorials/

 Tutorials Point: https://www.tutorialspoint.com/asp.net_core/index.htm

 Yogi Hosting: https://www.yogihosting.com/aspnet-core-introduction/

 DotNetTricks: https://www.dotnettricks.com/learn/aspnetcore

 CodeMaze: https://code-maze.com/getting-started-with-asp-net-core-mvc/

 Complete C# Tutorial: https://www.completecsharptutorial.com/aspnet-tutorial-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?

 What makes a request “appropriate” for a given action?

 Answer to these questions is routing.

 The server is able to determine what action to take based on the routing
configuration

 Routing—is the process of mapping an incoming HTTP request to a specific


handler. In MVC, the handler is an action method

 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

 Routing has two responsibilities:


 It maps the incoming requests to the Controller Action and

app's executable endpoints.

 Generate an outgoing URLs that correspond to Controller

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.

 Each route must have a unique name.

 Generally this name is only necessary when defining the


route, but it also provides the capability to access a
specific route in code if needed.
URL Pattern (Template)
 URL Pattern—can contain literal values contains both literal values,
such as a known string value and variable placeholders (referred to as
URL parameters). The literals and placeholders are located in
segments of the URL
 Route segment—is a piece of the URL, as delimited by slashes (/)
 Route segment—can be either constant (literal) or route parameter.
E.g., let's take the following URL path:
/User/Details/69/Faisal
 ASP.NET Core will parse this URL by splitting it into segments and
placeholder. We end up with four segments: User, Details, 69, Faisal
 Each route must contain a URL pattern. The URL Pattern is compared
to the incoming URLs for a match. If the pattern matches the URL, then
it is used by the routing system to process that URL.
URL Patterns (Template) …
 An example of URL Pattern is {controller=Home}/{action=Index}/{id?}

 Route Parameters are wrapped in curly braces e.g.: {controller}, {action}

 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

 This URL Pattern {controller=Home}/{action=Index}/{id?} Registers


route where the first part of the URL is Controller,
 The second part is the action method to invoke on the controller.
 The third parameter is an additional data in the name of id.
URL Patterns (Template) …
 You can define many different routing patterns:
 Each of the defined Pattern can set how a number of different URLs

map to a variety of action methods

 You can also have multiple patterns that all point to the same

action method from different URLs.

 Alternatively, you could have a pattern that would only match a

single URL, and maps to a single specific action


Route Defaults
 Defaults—Whenever you define a route with a variable placeholder, you have the
opportunity to assign a default value to that parameter. You can assign defaults to
every placeholder or not at all
 Defaults—will be used if values are not provided
 Defaults— is an object that contains default route values
 ASP.NET provides some default routing format {controller}/{action}/ {id}
 MVC configures the default route template as {controller=Home}/{action=Index}/{id?}
 This will match the Index() method in HomeController with an optional
parameter id by default.
 Any of the following URLs can be requested and they will be directed to the Index action
on the HomeController: / So, when a browser requests
/Home http://yoursite/ or
http://yoursite/Home it gets back the output
/Home/Index from HomeController’s Index method
URL Matching Example Exercise
 Each segment in the incoming URL is matched to the corresponding segment in the URL Pattern.
 The Route {controller=Home}/{action=Index}/{id?} has three segments. The last one is optional.
 Consider the Example URL www.example.com/product/list. This URL has two segments. This URL
Matches with the above pattern as the third segment in the URL Pattern is Optional
 The Routing engine will parse as {controller}= Product & {action}= List
 The URL www.example.com/product also matches with the above URL Pattern, although it has only
one segment. This is because the action placeholder has a default value of the Index. if there is no
corresponding segments are in the URL and segment has a default value in the Pattern, then the default
value is chosen by the Routing Engine. Hence this URL is parsed as
{controller}=Product and {action}=Index
 The www.example.com also matches with the above URL Pattern as the first segment controller has
the default value of Home. This URL is Parsed as {controller}=Home and {action}=Index
 The URL www.example.com/product/list/10 is parsed as {controller}=Home,{action}=Index and
{id}=10.
 The URL www.example.com/product/list/10/detail fails. That is because this URL has four segments
and the URL Pattern has three.
Route Constraints
 Route Constraints—a set of constraints to apply against the URL pattern to
more narrowly define the URL that it matches
 Route Constraints—helps us to filter out or restrict the unwanted types of
values from reaching the controller action by checking the Constraint against
the value of the URL Parameter. A route will only match if the data type of the
parameter matches, otherwise the request falls to the next matching route
 E.g., if we expect an argument that is a number we have to restrict it to an
integer type

 Route Constraints—are declared in attributes using curly brackets {id:int}


 Optional Constraint—adding a question mark to the constraints {id:int?}
indicates that the parameter is optional
 Route Constraints Types—bool, datetime, decimal, min, max, regex, etc.

 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?}");});

➢It has the third segment named id, which is Optional.


➢The id can be passed as the parameter to the Controller Action method.
➢Any route parameters except {controller} and {action} can be passed as parameters
to the action method
public string Index(string id) {
A request for /Home/Index/10
if (id !=null) {
return "Received " + id.ToString(); will match the above route and
} else {
return "Received the value 10 is passed as id
nothing";
} parameter to the Index action.
}
Endpoint
 Endpoint Routing was introduced in ASP.NET Core 2.2
 Endpoint Routing—is a system to handle routing across different
middleware systems (e.g. MVC, Razor Pages, Blazor, SignalR and gRPC).
 By having endpoints that work with each other, you can think of a system
more holistically then having terminal middleware that don't talk to each
other.
 Endpoints—are the app's units of executable request-handling code.

 Endpoints—are defined in the app and configured when the app starts

 Endpoint matching process—extract values from the request's URL and


provide those values for request processing. Using endpoint information
from the app, routing is also able to generate URLs that map to endpoints.
URL Generation
Routing—takes in a URL, uses the collection of routes, and outputs route values
URL Generation—it is the reverse process of routing
—takes in a collection of route values and uses the collection of routes to
output a URL
—used to generate outgoing URLs you can embed in your views so that users
can click links and submit forms back to your application in a way that will
target the correct controller and action
—eliminates hardcoding URLs, making your code more robust & maintainable
—address an important maintenance issue because the links are created
automatically based on the routes in your application. So if you change the
routes, the links created in the Views are automatically changed based on the
new route and you don’t have to manually change the links one by one.
URL Generation
 Generating URLs based on an action name
 You might need to generate URLs in a number of places in your

application, and one common location is in your controllers


 A link can be generated to the view page, using the Url helper from
the Controller base class.
public IActionResult Index()
{
var url = Url.Action("View", “Controller", new {Id =10});
return Content(${"The URL is {url}");
}
URL Generation …
 Generating URLs with ActionResults—when you want to redirect a user’s
browser to a particular action or route
 The RedirectToAction method takes in action and controller names, as well as
route parameters, and generates a URL in the same way as the Url.Action
method
public IActionResult RedirectingToAnActionMethod()
{
return RedirectToAction("View", "Controller", new { id = 10 });
}
 IUrlHelper, provide a number of different overloads to generate the correct URL
 Generating URLs in HTML—TagHelpers generate URLs through the form
TagHelper and the <a> TagHelper.

 Both of these use IUrlHelper for their implementation


Tag Helpers
 Tag Helpers
—are a new addition in ASP.NET Core MVC
—help us to add the server side code into our HTML in razor
markup using easy to use syntax
—look just like standard HTML code but it is processed by Razor
engine on the server giving it all the advantageous of server-side
rendering.
—reduce the explicit transitions between HTML and C# in Razor
views
—manipulate the HTML elements on which they are operated or
insert new HTML element, or replace the existing content with
the new one.
Tag Helpers Types
 Tag Helpers are of two types:

 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,

 Some common tag helpers are:

 Tag Helpers for Form, Input, Select, Label, Anchor, Text Area elements, CSS, JS

and Cache

 Custom Tag Helper—that can be created by you to perform your desired


transformation on an HTML element
How to use Tag Helpers?
 To use Tag helpers:
1. import the assembly Microsoft.AspNetCore.Mvc.TagHelper
2. add a @addTagHelper directive to view, or in specific views where you
want to use them

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

will be available to the view


How to use Tag Helpers?...
 Making the Tag Helpers available globally
 Adding the @addTagHelper to specific view makes it available only to
that view
 Add the @addTagHelper directive to the _ViewImports.cshtml, which
makes it to available in all the views.
 Removing the Tag Helpers—@removeTagHelper directive is used to
remove them from a specific view
@removeTagHelper ScriptTagHelper, Microsoft.AspNetCore.Mvc.TagHelpers
 Removing all the Tag Helpers
 Removes all the tag helpers from the assembly
Microsoft.AspNetCore.Mvc.TagHelpers from the specific view
@removeTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"
Form Tag Helper
Form Tag Helper—is bound to the HTML <form> element and renders an action
attribute within a form element . It also includes an anti-forgery token for request
verification
Some of the available attributes are:
 asp-controller: name of the MVC controller.to use
 asp-action: name of the MVC Controller action method to use
 asp-area: name of the Controller Area to use
 E.g.;: <form asp-controller="Home" asp-action="Create">
 The above code translated into
<form method="post" action="/Home/Create">
<input name="__RequestVerificationToken" type="hidden"
value="CfDJ8PlIso5McDBOjgPkVg9O4mnNiAE8U0HkVlA9e-Mtc”/>
</ form >
 Form tag helper has automatically inserted an Anti-forgery token into the generated
HTML
Label Tag Helper
Label Tag Helper
—is applied on the label HTML elements
—has one server-side attribute named asp-for
—used as shown below:
<label asp-for="@Model.Name"></label>
Which translates into
<label for="Name">Name</label>
The caption name is picked up from the model property name or
from the data annotations applied on the model property.
 Using @Model keyword is optional here. You can directly use the
model property name as shown:
<label asp-for="Name"></label>
Input Tag Helper
Input Tag Helper
—is applied to the input HTML elements
—has one server-side attribute named asp-for
—used as shown below:
<input asp-for="Name" />
Which translates into
<input type="text" id="Name" name="Name" value="" />

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

 asp-action: name of the MVC controller action method to use

 Such as in our demo application:


<a asp-controller=“Repository“ asp-action="Index">All Guests</a>
 The controller and action method those specified here must exist in the
current project
 The generated URL is placed in the href attribute of the anchor tag such as
<a href="/Repository/Index">All Guests</a>
What is a Layout?
 Most web apps have a common layout that provides the user
with a consistent experience as they navigate from page
to page. The content of the page changes. But the
contents of the menu, header, footer, color schemes do
not change. This gives the web pages a consistent look.
 Layout—defines a top level template for views in the app.
 Layout—typically includes common user interface elements such as the
app header, navigation or menu elements, sidebars and footer.
 Layouts and sections—in ASP.NET MVC core help us to maintain a
consistent look across all the pages or views of our application.
 Apps don't require a layout. Apps can define more than one layout, with
different views specifying different layouts.
The Layout of a Web Page
The design of the most websites includes a menu, a header, footer and sidebars.
A Typical page of an application looks as follows:
The layouts page
 To give a consistent look to web pages, we need to include the header, footer &
navigation menu to every view.

 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

@ViewBag.Title - The page title will be inserted here


@RenderBody() - The page content will be rendered here
RenderBody and RenderSection Methods
 Layout view uses two rendering methods:
RenderBody() and RenderSection()
 RenderBody—renders all the content of view which is not wrapped in
named section
 RenderBody—is a special method that marks the location where views
using this layout will have their content rendered
 RenderBody—acts as a placeholder for the Views
 RenderBody—can be used only once in the layout view
 RenderSection—renders the content of a view which is wrapped in
named section
 RenderSection—can be configured as required or optional. If required,
then all the child views must included that named section
 RenderSection—can be called multiple time with different name.
_ViewStart.cshtml
 Defining the layout in every view is harder to maintain.

 The simpler way is to define the layout in the _ViewStart.cshtml file

 _ViewStart.cshtml—is a special file and included in the Views folder by


default. The code in this file is executed before the code in an individual
view is executed. Instead of setting the Layout property in each individual
view, we can move that code into the _ViewStart.cshtml 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 multiple _ViewImports file in the project.

 One in each folder containing the views, like /Views/Books, /Views/Customers


etc. and each view file in those folders will pick up the view imports file in that
folder

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

The Layout Path


We used the full path ~/Views/Shared/_Layout.cshtml
partial path _Layout.
When a Partial path is provided the Razor view engine searches for the
layout file in the Views/{controller} folder first, and followed by the
Shared folder. This Process is identical to the searching for the Views
Removing the Layout from a View or Using another View
@{ @{
Layout = "null"; Layout = “SomeOtherLayout";
} }
Navigation Structure (Exercise)
 Goal of the navigation structure is to enable users to move easily and intuitively
from one page to another.
 When you look at the menu structure of a standard website, you are really
seeing nothing more than a way to move to a particular part of that site. Other
parts could be anything from a static “About Us” page to an e-commerce
product page that enables users to purchase a car. Each of those pages
represents a single resource—one specific request from the client browser
whereby the web server receives the request, performs some analysis on it, and
then determines how to respond in such a way that a specific resource fulfills
the request. (controller and action)
 The primary way to move from one location to another is through the HTML
anchor tag, <a href=“filename">Login to the Site</a>.
 This causes an HTTP request to be sent to the URL in the href attribute.
 Virtually every form of a navigational structure that you encounter is based on
this single HTML element.
 This means that when you create an ASP.NET MVC navigation structure, you
create the links yourself. However, you do not have to write them all by hand
because you can use the helpers.
Summary
 Routing

 Route Properties

 Configuring Routes

 Routes Examples

 URL Generation (for Navigation)

 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

University of Education Lahore, Multan Campus


Learning Objectives
 Model Binding

 Accessing Data Without Model Binding

 Model Validation

 Validation Attributes or Data Annotation Attributes

 Client Side, Server Side Validation

 Validation Helper Tags

 Passing Data into Views

 A Demo Application Describing the Model Binding, Model Validation


and passing data into views
Summary of Last Lecture
 Routing

 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
Online Resources
 Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/core/

 Tutorials Teacher: https://www.tutorialsteacher.com/core

 Dot Net Tutorials: https://dotnettutorials.net/course/asp-net-core-tutorials/

 Tutorials Point: https://www.tutorialspoint.com/asp.net_core/index.htm

 Yogi Hosting: https://www.yogihosting.com/aspnet-core-introduction/

 DotNetTricks: https://www.dotnettricks.com/learn/aspnetcore

 CodeMaze: https://code-maze.com/getting-started-with-asp-net-core-mvc/

 Complete C# Tutorial: https://www.completecsharptutorial.com/aspnet-tutorial-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

 you focus on the important aspects of your application i.e.,


the business requirements
Model Binding Sources
 Model binder—looks implicitly for a match in the following binding sources
in order and will take the first value it finds (if any) that matches the name of
the parameter, Each of these binding sources store values as name-value
pairs.
 Form fields—Sent in the body of an HTTP request when a form is sent to
the server using a POST
 Route values—Obtained from URL segments or through default values
after matching a route.
 Query strings—Passed at the end of the URL, not used during routing

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

 But it updates ModelState object with the list of errors and


sets the isValid property to false.

 Hence, checking for ModelState.isValid tells us whether


the model binding succeeded or not
Accessing Data Without Model Binding
 HttpContext object—holds information about the current HTTP
request like:
 Request, Response, Server, Session, Cache, User and etc.

 A new HttpContext object will be created at the beginning of a request


and destroyed when the request is completed.
 HttpContext.Request - all members related to the current request, e.g. the
QueryString, Forms and so on.
 HttpContext.Response - all members related to the Response about to be
delivered, e.g. Cookies and response headers
 HttpContext.Session - all members related to dealing with Session
(generally used to persist data between requests)
 HttpContext.User - all members related to dealing with a (potentially)
authenticated user
Accessing the HTML Forms directly
 To do that we need to access the Request object to access the
values—the data.
[HttpPost]
public IActionResult NoModelBinding()
{
ProductEditModel model = new ProductEditModel();
string message = "";

model.Name = Request.Form["Name"].ToString();
model.Rate = Convert.ToDecimal(Request.Form["Rate"]);
model.Rating =Convert.ToInt32(Request.Form["Rateing"]);

message = "product " + model.Name + " created successfully";


return Content(message);
}
Query String & Request Headers Data
 Accessing the query string directly
 Similarly, you can access the query string values directly using the Request.Query
collection, which is parsed from the Query String.

 E.g.: Request.Query[“id”].ToString() returns the value of id query string

 The Request.QueryString.HasValue will let you know if the Query string is


present in the URL and Request.QueryString.Value will return the raw query
string

 Accessing the Request Headers directly

 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

 You can never rely on it because


 It will always be possible to bypass these browser protections
 JavaScript may be disabled in the end users browser
 An Error in Javascript code may result in validation to succeed although data
is invalid

 Hence, it is important to validate the data completely at the server


side, even though you have done those validations at the client side
Validation or Data annotation attributes
➢ Data annotation attributes
—allow you to specify rules that the properties in your model should conform to.
—provide metadata about your model by describing the sort of data the model should
contain, as opposed to the data itself
➢ Metadata—describes other data, specifying the rules and characteristics the data should
adhere to
—uses System.ComponentModel.DataAnnotations namespace to do validations at the
model level

—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)]

 DataType—is used to specify the datatype of the model.


 Syntax: [DataType(DataType.Text)]

 Range—is use to set a range between two numbers.


 Syntax: [Range(100,500,ErrorMessage="Please enter correct value")]

 StringLength—use to specify maximum and minimum length of the


property
 Syntax: [StringLength(30,ErrorMessage="Do not enter more than 30
characters")]
Data Annotations Attributes Description…
 DisplayName—used to specify property name to be displayed on view.

 Syntax: [Display(Name="Student Name")]

 MaxLength—used to specify maximum length of property

 Syntax: [MaxLength(3)]

 Bind—used to specify fields to include or exclude for model binding.

 Syntax: [Bind(Exclude = "StudentID")]

 DisplayFormat—allows us to set date in the format specified as per the attribute

 Syntax: [DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")]

 RegularExpression—use to set a regex pattern for the property. E.g. Email ID


Validation Tag Helpers in ASP.NET Core
 Model binder—binds and validates the data received over the HTTP
Request. It then creates the ModelState object, which contains the
validation messages generated by the Model Binder.

 Validation Tag helpers—generate the HTML element to display


these (validation) messages in the view

 There are two Validation Tag Helpers which display the validation
messages to the user (on the client side):

 Validation Message Tag Helper

 Validation Summary Tag Helper


Validation Message Tag Helper
 Validation message tag—helper targets the <span> element and is used to display a
validation message for the property specified in its attribute.
 E.g.: <label asp-for="Name">Name</label>
<input asp-for="Name" />
 [Required] <span asp-validation-for="Name"></span>
 Public string name {get;set;} <br />

 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

 Use HTML5 Built-in Validation

 Write your own Javascript

 ASP.NET core includes unobtrusive client-side validation libraries— which makes


it easier to add client side validation code, without writing a single line of code

 Unobtrusive client side validation in ASP.NET Core—uses the same attributes to


validate the properties used by the Model Validator on the client side. The difference
is that it uses the Javascript instead of C# code
How to use unobtrusive client-side validation
 Unobtrusive validation—is done using the jquery.validate.unobtrusive.js library.

 This library is built over the top of jquery.validate.js library, which in turns uses the
jQuery

 Hence we need to import all these in our views:


 Load the required javascript libraries
 First, we need to add the JQuery,jquery.validate & jquery.validate.unobtrusive in our views

 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>

 <script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"> </script>


Passing Data into Views
 For passing data from the controller into the views, we can use two approaches:
 Strongly Typed Data
 Weakly Typed Data
 Strongly Typed Data—we pass a view model from the controller into the view
 View model—should be used to encapsulate any data that needs to be displayed in
a view, It’s a strongly typed class that can be any sort of object you like.

 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

 Accessing Data Without Model Binding

 Model Validation

 Validation Attributes or Data Annotation Attributes

 Client Side, Server Side Validation

 Validation Helper Tags

 Passing Data into Views

 A Demo Application Describing the Model Binding, Model Validation


and passing data into views
Thank You
ITEC 4116
Advance Web Application Development

Lecture 23

Fayyaz Muhammad
Assistant Professor

University of Education Lahore, Multan Campus


Learning Objectives
 State Management
 Cookies
 Sessions
 TempData
 Query String
 Hidden Fields
 Cache, Caching, Response Based Caching
 Different Options in Caching in ASP.NET Core
 Database Application Demo
Summary of Last Lecture
 Model Binding

 Accessing Data Without Model Binding

 Model Validation

 Validation Attributes or Data Annotation Attributes

 Client Side, Server Side Validation

 Validation Helper Tags

 Passing Data into Views

 A Demo Application Describing the Model Binding, Model


Validation and passing data into views
Online Resources
 Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/core/

 Tutorials Teacher: https://www.tutorialsteacher.com/core

 Dot Net Tutorials: https://dotnettutorials.net/course/asp-net-core-tutorials/

 Tutorials Point: https://www.tutorialspoint.com/asp.net_core/index.htm

 Yogi Hosting: https://www.yogihosting.com/aspnet-core-introduction/

 DotNetTricks: https://www.dotnettricks.com/learn/aspnetcore

 CodeMaze: https://code-maze.com/getting-started-with-asp-net-core-mvc/

 Complete C# Tutorial: https://www.completecsharptutorial.com/aspnet-tutorial-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

 Cookies—are generally the most durable form of data persistence on


the client
Session State
 Session state—is a mechanism to store user data while the user
browses the application

 Session state—uses a store maintained by the app to persist data


across requests from a client

 Session State—are maintained by ASP.NET Core by providing a


cookie to the client that contain a session ID,

 The cookie session ID:

 is sent to the app with each request

 is used by the app to fetch the session data


Session State Behavior
Session state exhibits the following behaviors:
 A Session cookie is specific to the browser session, Sessions aren't shared
across browsers.
 When a browser session ends, it deletes the session cookie
 If an app receives a cookie for an expired session, it creates a new session
that uses the same session cookie

 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

 Critical app data should be:

 stored in the user’s database

 cached in a session only as a performance optimization if required


TempData
 TempData—stores data until it is read in another request
 TempData—is particularly useful when we require the data for more
than a single request. We can access them from controllers and views.
 TempData—is available when we read it for the first time and then it
loses its value.
 What if we need to persist the value of TempData even after we read it?
 There are two methods to do that:
 TempData.Keep()/TempData.Keep(string key) method—retains the
value corresponding to the key passed in TempData. If no key is passed, it
retains all values in TempData.

 TempData.Peek(string key) method—gets the value of the passed key


from TempData and retains it for the next request.
TempData Providers
 ASP.NET provides two TempData providers:
 Cookie based

 Session State based

 Cookie based TempData—used by default. This means TempData


values are stored in cookies on the client machine
 Since TempData is stored in cookies you don't need Session state
enabled through the session state middleware. Just store and
retrieve TempData key-value pairs as you normally do
 Storing TempData in cookies can be useful when:

 the data being stored in TempData is small in size

 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

 Session state based TempData—can come handy when your app


is already using session state for other purposes.

 Session state based TempData—if you intend to store bigger


chunks of data in TempData cookie based storage might not serve
the purpose and you may want to switch to session based
Query strings
 Query string—is a part of the request that appears after the question
mark (?) character in the URL
 Query string—provides a simple way to pass a limited amount of data
from one page to another (one request to another) by adding it to the
new request’s query string
 This is useful for page number state or search terms and for capturing state
in a persistent manner that allows links with embedded state to be shared
through email or social networks
 Never use query strings for sensitive data as URL query strings are public
 In addition to unintended sharing, including data in query strings can
expose the app to Cross-Site Request Forgery (CSRF) attacks.
 Any preserved session state must protect against CSRF attacks
Hidden Fields
 Hidden field—is used to hide your data on client side
 Hidden form fields—can save data and send back in the next request
 Sometimes we require some data to be stored on the client side
without displaying it on the page. Later when the user takes some
action, we’ll need that data to be passed on to the server side.
 This is a common scenario in many apps (multi-page forms) and
hidden fields provide a good solution for this.
 Because the client can potentially tamper with the data, the app must
always revalidate the data stored in hidden fields
 So, this is not recommended if you want to store a sensitive data. It’s
only used to store a small amount of data which is frequently changed
Cache
 Cache—is a hardware or software component that stores data so that
future requests for that data can be served faster;
 Cache—store data that might be the result of an earlier computation
or a copy of data stored elsewhere.
 Cache hit—occurs when the requested data can be found in a cache and is
served by reading data from the cache, which is faster than recomputing a
result or reading from a slower data store; thus, the more requests that can
be served from the cache, the faster the system performs
 Cache miss—occurs when it cannot find the requested data
 Caching—is an efficient way to store and retrieve data for improving
web app performance by temporarily storing requested data in
memory for later reuse
 App can control the lifetime of cached items
ASP.NET Core Response Caching
 Response caching—enables you to cache the server responses of a
request so that the subsequent requests can be served from the cache
 Response caching—is controlled by cache-related headers in the HTTP
responses that specify how you want client, proxy, and middleware to
cache responses
 Response caching—reduces the number of requests a client or proxy
makes to a web server
 Response caching—also reduces the amount of work the web server
performs to generate a response, it takes off processing load from the
servers as they do not need to process and generate a response for the
same request again
 Response caching—boosts app performance as the response is served
from the cache
 Response caching—key benefits include reduced latency and network
traffic, improved responsiveness, and hence improved performance.
Response Caching Options
 ASP.NET Core provides support for response caching using the
response caching middleware.

 ASP.NET Core provides support for several different types of


caching include:

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

 When cached data is distributed, the data:


 is coherent (consistent) across requests to multiple servers.
 survives server restarts and app deployments.
 doesn’t use local memory

 Two main disadvantages of the shared caching approach:


 the cache is slower to access because it is no longer held locally to each app
instance
 the requirement to implement a separate cache service might add complexity
to the solution
Key points about Caching
 Use caching for contents that are accessed frequently.
 Cached data isn't associated with a specific request, user, or session.
Avoid caching for contents that are unique per user that may be
retrieved by other user requests
 Avoid caching for contents that are accessed infrequently/rarely.
 Use the VaryByCustom function to cache multiple versions of a page
based on customization aspects of the request such as cookies, role,
theme, browser, and so on
 For efficient caching use 64-bit version of Windows Server and SQL
Server
 For database caching make sure your database server has sufficient
RAM otherwise, it may degrade the performance.
 For caching of dynamic contents that change frequently, define a short
cache–expiration time rather than disabling caching.
Statelessness and Web Database App
 Statelessness has benefits:
 the most significant are the resource savings from not having to maintain
information at the web server to track a user or requests
 the flexibility to allow users to move between unrelated pages or resources
 However, because HTTP is stateless, it is difficult to develop stateful web
database apps: E.g.: it’s hard to force a user to follow menus or a series of
steps to complete a task
 Web Apps—process data that is shared between web components and is persistent
between invocations of a web app is usually maintained by following ways:
 Date can be stored on the local file system as a specially delimited file.
 Another, and the most common, way to store information is in a database
system.
 Database system—is an application whose primary reason for existence is to
manage the creation, editing, deletion, and fetching of data
Summary
 State Management

 Storing user-specific data in browser Cookies.

 Using Session State to store data related to a user session.

 Use TempData to pass data from a controller action method to another or a View.

 Passing data between requests using Query Strings.

 Using Hidden Fields to store data that are not displayed on a page.

 Caching, Response Based Caching

 Different Options in Caching in ASP.NET Core

 Database Application Demo


Thank You
ITEC 4116
Advance Web Application Development

Lecture 25 AJAX, jQuery

Fayyaz Muhammad
Assistant Professor

University of Education Lahore, Multan Campus


Learning Objectives
 AJAX

 jQuery

 jQuery AJAX Methods


Summary of Last Lecture
 Database Application

 ADO.NET

 ADO.NET Components

 Data Providers and DataSet

 Connection, Command, DataReader and DataAdapter

 Connection String

 .NET Data Provider for SQL Server

 Database Demo Application


Online Resources
 Microsoft Docs: https://docs.microsoft.com/en-us/aspnet/core/

 Tutorials Teacher: https://www.tutorialsteacher.com/core

 Dot Net Tutorials: https://dotnettutorials.net/course/asp-net-core-tutorials/

 Tutorials Point: https://www.tutorialspoint.com/asp.net_core/index.htm

 Yogi Hosting: https://www.yogihosting.com/aspnet-core-introduction/

 DotNetTricks: https://www.dotnettricks.com/learn/aspnetcore

 CodeMaze: https://code-maze.com/getting-started-with-asp-net-core-mvc/

 Complete C# Tutorial: https://www.completecsharptutorial.com/aspnet-tutorial-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

 jQuery—and other JavaScript libraries make it much easier to take


advantage of JavaScript

 jQuery—is a JavaScript library designed to simplify HTML DOM tree traversal


and manipulation, as well as event handling, CSS animation, and AJAX.

 jQuery—is free, open-source software using the permissive MIT License


 jQuery—enables JavaScript programmers to code without worrying about
differences among browsers without writing very much code.
AJAX with jQuery
 Different browsers implement the AJAX differently that means:
 if you're adopting the typical JavaScript way to implement the AJAX you have to
write the different code for different browsers to ensure that AJAX would work
cross-browser

 jQuery—simplifies the process of implementing AJAX by taking care


of those browser differences, so that we can write AJAX functionality
with only one single line of code. That is One of the primary reasons
programmers started adopting JavaScript libraries

 jQuery—includes various simple methods to send AJAX requests that


works seamlessly across browsers. These methods internally use
XMLHttpRequest object of JavaScript:
 $.ajax(), load(), $.get(), $.post(), etc.
jQuery Development Tools
 jQuery development—requires an editor to write a jQuery code and jQuery
library

 Editor—You can use any JavaScript editor to write jQuery code including following:
 Notepad
 Visual Studio
 Eclipse
 Aptana Studio
 Ultra edit

 An editor—which supports IntelliSense for JavaScript and jQuery functions will


increase a developer's productivity.

 jQuery Library—to download jQuery library, go to jquery.com


Using jQuery Library
 After downloading an appropriate version of jQuery library, you can use it by taking a
reference of it in your web page.
 jQuery—is a regular JavaScript file that you can include in your page using the
<script> tag as below.
<!DOCTYPE html>
<html>
<head>
<script src="~/Scripts/jquery-3.3.1.js"></script>
</head>
<body>
</body>
</html>
Include jQuery Library from CDN—You can also reference jQuery library from public CDN
(content delivery network) such as Google, Microsoft, CDNJS, jsDelivr etc.
jQuery Important Features
 DOM Selection: jQuery provides Selectors to retrieve DOM element based on different
criteria like: Tag name, id, CSS class name, attribute name, value, nth child in hierarchy

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

 Cross-browser support: jQuery library automatically handles cross-browser issues,


so the user does not have to worry about browsers without writing extra code

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

 Excellent API Documentation: jQuery provides excellent online API documentation.

 Unobtrusive: jQuery is unobtrusive which allows separation of concerns by


separating html and jQuery code.
Start Using jQuery
 jQuery—is built around the idea of selecting objects on the page and
then performing actions on them.
 jQuery—in some ways, is very similar to CSS. You use a selector to
define an element or set of elements, and then you write some code
that is applied to those elements.
 jQuery—adds a global function named jQuery after jQuery library
successfully loaded
 The global scope means scope of the window, so the global jQuery()
function can be called like window.jQuery() or jQuery() anywhere in
your web page.
Start Using jQuery…
 In jQuery—the dollar sign ($) is just an alias for jQuery.
 $ is a short form of jQuery function.
 $() = jQuery() = window.$() = window.jQuery()

 $()/jQuery()—is a selector function that selects DOM elements


Start Using jQuery…
 jQuery() (aka $)—takes two parameters, selector and context
 Selector—can be CSS style selector expression for matching a set of elements
in a document E.g., if you want to do something with all the div elements then use $
function to match all the div elements as shown below. E.g.: Selector Parameter

jQuery('div’) OR window.jQuery('div’) OR $('div’) OR window.$('div’)

 Context—can be anything, it can be reference of another DOM element or it


can be another jQuery selector
 jQuery—will start searching for the elements from the element specified in a context

 jQuery selector may performs faster if you provide context parameter.

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

 $(document).ready()—determines when the full DOM hierarchy is loaded


whereas window.onload event is raised when entire window is loaded including
DOM, images, CSS and other required resources. The DOM loads before entire
window loads
jQuery Execution Steps
The Steps in jQuery execution:

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:

jQuery AJAX Events Description


ajaxComplete() Register a handler function to be called when AJAX requests
complete.
ajaxError() Register a handler function to be called when AJAX requests
complete with an error.
ajaxSend() Register a handler function to be called before AJAX request is
sent.
ajaxStart() Register a handler function to be called when the first AJAX request
begins.
ajaxStop() Register a handler function to be called when all the AJAX requests
have completed.
ajaxSuccess() Register a handler function to be called when AJAX request
completes successfully.
jQuery ajax() Method
 ajax() method—provides core functionality of AJAX in jQuery
 ajax() method—sends asynchronous HTTP requests to the server
and gets the data from the server
 ajax() method—can be used to send http GET, POST, PUT, DELETE
etc. request. It can retrieve any type of response from the server.
 Syntax:
$.ajax(url);
$.ajax(url,[options]);
 Parameter description:
 url: A string URL to which you want to submit or retrieve the data
 options: Configuration options for AJAX request. An options
parameter can be specified using JSON format. This parameter is
optional.
jQuery ajax() Method Example
 The load(), get() and post() methods relay on ajax() behind the scene.
 ajax() has lot of different property
 How to send a simple AJAX request.
$.ajax('/jquery/getdata', // request url
{
success: function (data, status, xhr) {// success callback function
$('p').append(data);
}
});
<p></p>
jQuery load() Method
 load() method—is a simple, but powerful AJAX method.
 load() method—is used to load any static or dynamic data (HTML or Text
Contents) from a server and puts the returned data into the selected DOM
Element
 Syntax: $(selector).load(URL, data ,callback);
 URL—URL of the server-side resource to which the request is sent. It could be
a CGI, ASP, JSP, or PHP script which generates data dynamically or out of a
database
 data—optional parameter, represents an object whose properties are
serialized into properly encoded parameters to be passed to the request. If
specified, the request is made using the POST method. If omitted, the GET
method is used.
 callback − A callback function invoked after the response data has been loaded
into the elements of the matched set. The first parameter passed to this
function is the response text received from the server and second parameter is
the status code.
load() method example
$(document).ready(function() {

$("#myButton").click(function(){

$("#myDiv").load('Sample.html')

})

});
jQuery get() method
 get() method—sends asynchronous HTTP GET request to the server
and retrieves the data

 Syntax: $.get(URL, callback);


 URL—required URL parameter specifies the URL you wish to request

 callback—optional callback parameter is the name of a function to be


executed if the request succeeds
jQuery post() method
 post() method—sends asynchronous HTTP POST request to the
server to submit the data to the server and get the response.

 Syntax: $.post(URL, data, callback);


 URL—required URL parameter specifies the URL you wish to request.

 data—optional data parameter specifies some data to send along


with the request.

 callback—optional callback parameter is the name of a function to be


executed if the request succeeds.
Summary
 AJAX

 jQuery

 jQuery AJAX Methods


Thank You

Вам также может понравиться