0% found this document useful (0 votes)
84 views346 pages

Core MVC

This document provides an overview and outline of a course on developing ASP.NET Core MVC web applications. The course will cover topics such as exploring ASP.NET Core MVC, designing web applications, developing controllers, views, and models, using Entity Framework Core and connecting to databases, and testing and deploying applications. It will also cover client-side development using CSS, JavaScript, and jQuery.

Uploaded by

ebunoluwakamikun
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
84 views346 pages

Core MVC

This document provides an overview and outline of a course on developing ASP.NET Core MVC web applications. The course will cover topics such as exploring ASP.NET Core MVC, designing web applications, developing controllers, views, and models, using Entity Framework Core and connecting to databases, and testing and deploying applications. It will also cover client-side development using CSS, JavaScript, and jQuery.

Uploaded by

ebunoluwakamikun
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 346

Developing ASP.

NET Core
MVC Web Applications
Welcome!

Thank you for joining us today.

We’ve worked together with Microsoft Learning Partners and


Microsoft IT Academies to bring you a world-class learning
experience, including:

• Microsoft Certified Trainers + Instructors: Your instructor is


a premier technical and instructional expert who meets ongoing
certification requirements.

• Customer Satisfaction Guarantee: Our Partners offer a


satisfaction guarantee and we hold them accountable for it. At
the end of class, please complete an evaluation of today’s
experience. We value your feedback!

• Certification Benefits: After training, consider pursuing a


Microsoft Certification, to help distinguish your technical
expertise and experience. Ask your instructor about available
exam promotions and discounts.

We wish you a great learning experience and ongoing


career success!
Meet the Instructor

Instructor: <Instructor Name>

<Title or other credentials, e.g. Microsoft


Certified Trainer>

<Affiliation/Company>

<A few words about my technical and


professional experience>
Facilities

Class hours Building hours Parking

Restrooms Meals Phones

Messages Smoking Recycling

5
About This Course

Course
Audience Prerequisites

COURSE

Course What you


Objectives can Expect
About the Course
Audience

This course is intended for professional web

developers who use Visual Studio in an

individual-based or team-based scenario in

small to large development environments.

Candidates for this course are interested in

developing advanced web applications and

want to manage the rendered HTML

comprehensively. They want to create

websites that separate the user interface,

data access, and application logic.

© 2023 elev8 - All rights reserved. 8


Prerequisites

Candidates who attend this course typically are IT

professionals who have:

• Experience with Visual Studio 2017.

• Experience with C# programming and concepts such as

Lambda expressions, LINQ, and anonymous types.

• Experience in using the .NET Framework.

• Experience with HTML, CSS, and JavaScript.

• Experience with querying and manipulating data with

ADO.NET.

• Knowledge of XML and JSON data structures.

© 2023 elev8 - All rights reserved. 9


Objectives

After completing this course, students will be able to:

• Describe the Microsoft Web Technologies stack and select an appropriate technology to use to

develop any given application.

• Design the architecture and implementation of a web application that will meet a set of functional

requirements, user interface requirements, and address business models.

• Configure the pipeline of ASP.NET Core web applications by using middleware and leverage

dependency injection across Model-View-Controller (MVC) applications.

• Add controllers to an MVC application to manage user interaction, update models, and select and

return views.

• Develop a web application that uses the ASP.NET Core routing engine to present friendly URLs and a

logical navigation hierarchy to users.

© 2023 elev8 - All rights reserved. 10


Objectives

After completing this course, students will be able to:

• Create views, which display and edit data and interact with models and controllers, in an MVC

application.

• Create MVC models and write code that implements business logic within model methods, properties,

and events.

• Connect an ASP.NET Core application to a database by using Entity Framework Core.

• Implement a consistent look and feel across an entire MVC web application.

• Write JavaScript code that runs on the client-side and utilizes the jQuery script library to optimize the

responsiveness of an MVC web application.

• Add client side packages and configure Task Runners

© 2023 elev8 - All rights reserved. 11


Objectives

After completing this course, students will be able to:

• Run unit tests and debugging tools against a web application in Visual Studio 2017.

• Write an MVC application that authenticates and authorizes users to access content securely by using

Identity.

• Build an MVC application that resists malicious attacks.

• Use caching to accelerate responses to user requests.

• Use SignalR to enable two-way communication between client and server.

• Describe what a Web API is and why developers might add a Web API to an application.

• Describe how to package and deploy an ASP.NET Core MVC web application from a development

computer to a web server.

© 2023 elev8 - All rights reserved. 12


Course Outline

• Module 1: Exploring ASP.NET Core MVC • Module 7: Using Layouts, CSS, and JavaScript

in ASP.NET Core MVC


• Module 2: Designing ASP.NET Core MVC Web

Applications • Module 8: Client-Side Development

• Module 3: Developing Controllers • Module 9: Testing and Troubleshooting

• Module 4: Developing View • Module 10: Managing Security

• Module 5: Developing Models • Module 11: Performance and Communication

• Module 6: Using Entity Framework Core in • Module 12: Implementing Web APIs

ASP.NET Core
• Module 13: Hosting and Deployment

13
Module 01
Exploring ASP.NET Core MVC

14
Module Overview

Overview of ASP.NET
01
Overview of Microsoft
Web Technologies 02 4.x

Introduction to
03 ASP.NET Core MVC
Lesson 1: Overview of Microsoft Web Technologies

01 02 03 04
Introduction to Overview of Client-Side Web Hosting
Microsoft Web ASP.NET Technologies Technologies
Technologies
Introduction to Microsoft Web Technologies

Develop Host Execute

Server-Side Client-Side

• Visual • IIS • ASP.NET • JavaScript


Studio • Microsoft Core • jQuery
• Visual Azure • ASP.NET • Angular
Studio Code 4.x • React
• AJAX
Introduction to Microsoft Web Technologies

Develop Host Execute

Server side Client Side


• Visual Studio • IIS • ASP.NET • JavaScript
Core
• Visual Studio • Microsoft • jQuery
Code Azure • ASP.NET 4.x
• Angular
• React
• AJAX
Overview of ASP.NET

• Programming Models:
ASP.NET
• ASP.NET 4.x:

• Web Pages

• Web Forms

• ASP.NET 4.x and ASP.NET Core: HTML


Pages
• MVC

• Web API

• ASP.NET Core:

• Razor Pages
Client-Side Web Technologies

<p>
• JavaScript
Content
• jQuery </p>

• AJAX p{
color: black;
• Angular }

• React

• And more
Hosting Technologies

• IIS

• Features

• Scaling

• Perimeter Networks

• IIS Express

• Other Web Servers


Microsoft Azure

• Cloud computing provides scalability,

flexibility, security, and reliability

• The Microsoft Azure platform includes:

• Web Apps

• Databases (Azure SQL Database,


Cosmos DB)

• Virtual Machines

• Mobile Apps

• Media Services
Lesson 2: Overview of ASP.NET 4.x

01 02 03
Overview of Web Overview of Web Overview of MVC
Pages Forms

04 05 06
Discussion: Shared ASP.NET Overview of Web
ASP.NET 4.x 4.x Features API
Application
Scenarios
Overview of Web Pages

• Code in .CSHTML files


• Precise control over HTML

<h2>Special Offers</h2>
<p>Get the best possible value on Northwind specialty
foods by taking advantage of these offers:</p>
@foreach (var item in offers) {
<div class="offer-card">
<div class="offer-picture">
@if (!String.IsNullOrEmpty(item.PhotoUrl)){
<img src="@Href(item.PhotoUrl) alt="@item.Title" />
}
</div>
</div>
}
Overview of Web Forms

• Code in .aspx files and code-behind files

• Create a UI by dragging controls onto a page

• Controls provide rich properties and events

• Bind controls to data


Overview of MVC

• Models encapsulate objects and data

• Views generate the user interface

• Controllers interact with user actions

• Code in .cshtml and .cs files

• Precise control of HTML and URLs

• Easy to use unit tests


Discussion
Discussion: ASP.NET 4.x Application Scenarios

Which programming model will you use in the following scenarios?


(Choose one of the following in each scenario: MVC, Web Forms, Web Pages)

• A database front-end to be hosted on an intranet

• An e-commerce site for a large software organization

• A website for a small charitable trust


Shared ASP.NET 4.x Features

Configuration Authentication Membership and Roles

State Management Caching


Overview of Web API

• Helps creating RESTful APIs

• Enables external systems to use your application's business logic

• Accessible to various HTTP clients

• Helps to obtain data in different formats such as JSON and XML

• It supports create, read, update and delete (CRUD) actions

• Ideal for mobile application integration


Lesson 3: Introduction to ASP.NET Core MVC

01 02 03
Introduction to Discussion: Choose between
ASP.NET Core Choose between .NET Core and
ASP.NET 4.x and .NET Framework
ASP.NET Core

04 05
Models, Views, Demonstration:
and Controllers How to Explore
an ASP.NET Core
MVC Application
Introduction to ASP.NET Core

• ASP.NET Core is:

• Modern redesign of ASP.NET 4.x

• Cross-platform and open source

• Lean, high-performance and modular framework

• Cloud-ready

• Supports the following programming models:

• MVC

• Razor pages

• Web API
Razor Pages

Alternative to the MVC programming model


Starts with the @page directive

@page
@model HomePageModel

<h1>@Model.Title</h1>
<h2>@Model.Description</li>
Discussion
Choose between ASP.NET 4.x and
ASP.NET Core
Choose between .NET Core and .NET Framework

You should use .NET Core when: You should use .NET Framework when:

• You want your code to run cross- • You want to extend an existing
platform application that uses .NET Framework
• You want to create microservices • You want to use NuGet packages or
• You want to use Docker containers third-party .NET libraries that are not
• You want to achieve a high-preforming supported in .NET Core
scalable system • You want to use .NET technologies that
aren't supported in .NET Core
• You want to use a platform that doesn’t
support .NET Core
Models, Views, and Controllers

SQL
View Model

Database

Controller

HTTP
Web Server

Browser
Demonstration: How to Explore an ASP.NET Core
MVC Application

In this demonstration, you will:

• Examine an ASP.NET Core MVC application


that renders the default home page

• Examine the Index View code

• Examine the default route used to map


requests to the controller

• Examine the Home Controller code

• Examine the Photo Model code

• Examine the photo list rendered as a result


of models, controllers, and views working
together
Module 1 Lab: Exploring ASP.NET
Core MVC
Labs And Exercises
Module Review
and Takeaways
Module 02
Designing ASP.NET Core MVC Web
Applications

40
Module Overview

Designing Models,
01
Planning in the Project
Design Phase 02 Controllers and Views
Lesson 1: Planning in the Project Design Phase

01 02 03 04
Project Gathering Planning the Planning for
Development Requirements Database Design Distributed
Methodologies Applications

05 02 03
Planning State Planning Planning
Management Globalization and Accessible Web
Localization Applications
Project Development Methodologies

Development
Description
Model
Waterfall Model Activities for building an application are performed sequentially in distinct phases with clear
deliverables.
Iterative Activities for building an application are performed iteratively in parts by using working
Development Model versions that are thoroughly tested, until it is finalized.
Prototype Model Activities for building an application are based on a few business requirements, and a
prototype is made. Feedback on the prototype is used as an input to develop the final
application.
Agile Development Activities for building an application are performed in rapid cycles, integrating changing
Model circumstances and requirements in the development process.
Extreme Activities for building an application begin with solving a few critical tasks. Developers test the
Programming simplified solution and obtain feedback from stakeholders to derive the detailed requirements,
which evolve over the project life cycle.
Test Driven Activities for building an application begin with a test project. Changes to the code can be
Development tested singly or as a group, throughout the project.
Unified Modeling Activities for building an application begin with UML diagrams that are used for planning and
Language documenting purposes, across all project development models.
Waterfall Model Activities for building an application are performed sequentially in distinct phases with clear
deliverables.

© 2023 elev8 - All rights reserved. 43


Gathering Requirements

• Functional requirements describe how the application

responds to users

• Technical requirements describe the technical


features of an application, such as availability,
security, or performance

• You can build functional requirements by using:

• Usage scenarios

• Use cases

• Requirements modeling in the agile methodology

• User stories in the extreme programming Sample UML Use Case Diagram

methodology
Planning the Database Design

Logical modeling Physical database


structure

Database design in
Working with DBAs agile and extreme
programming
Planning for Distributed Applications

• Layers Browser

• Presentation

• Business logic Web


Server Presentation
• Data access

• Database
Middle Business Logic
• Communication Tier Data Access
Server
• Security

Database
Server
Planning State Management

• Client-side locations to store state data:

• Cookies

• Query strings

• Server-side locations to store state data:

• TempData

• Application state

• Session state

• Database tables
Planning Globalization and Localization

01 02 03
You can use the You can use resource You can use separate
internationally- files to provide a views to suit each
recognized set of localized response language code
language codes suitable to a user’s
available in browsers to culture
present content
customized to suit a
user’s language or
region
Planning Accessible Web Applications

You can ensure that your content is accessible to the broadest range of users by adhering to
the following guidelines:

• Provide alt attributes for visual and auditory content

• Do not rely on color to highlight content

• Separate content from structure and presentation code:

• Only use tables to present tabular content

• Avoid nested tables

• Use <div> elements and positional style sheets to lay out elements on the page

• Avoid using images that include important text

• Put all important text in HTML elements or alt attributes


Lesson 2: Designing Models, Controllers and Views

Designing Models Designing Controllers

Designing Views Information


Architecture
Designing Models

• Model classes and properties

• Using diagrams

• Relationships and aggregates

• Entity framework

• Design in agile and extreme programming


Designing Controllers

Controller Action

AddPhoto (GET)
Photo AddPhoto (POST)
DisplayGallery (GET)
Logon (GET)
User
Logon (POST)

• Identify controllers and actions

• Design in agile and extreme programming


Designing Views

• Views Adventure Works Photo Sharing Log On

• Layouts Home Gallery Slideshow

• Partial views and view


components Photo

• Design in agile and

extreme programming Add Comment


Information Architecture

MVC Model:
Planning a logical hierarchy • Boiler
• Category
• FAQQuestion
Presenting a hierarchy in • Installation Manual
navigation controls • User Manual

Presenting a hierarchy in URLs Information Architecture:


• Category
• Furnace
• FAQQuestion
• Installation Manual
• User Manual
Module 2 Lab: Designing ASP.NET
Core MVC Web Applications
Labs And Exercises
Module Review
and Takeaways
Module 03
Developing Controllers

57
Module Overview

01
Writing Controllers and
Actions 02 Configuring Routes

03 Writing Action Filters


Lesson 1: Writing Controllers and Actions

01 02 03 04 05
Responding to Writing Using Using ViewBag Demonstration:
User Requests Controller Parameters and ViewData to How to Write
Actions Pass Information Controllers and
to Views Actions
Responding to User Requests
Writing Controller Actions

• An action is a public method of the controller class

• Actions can return objects that implement the IActionResult interface

public class HomeController : Controller


{
public IActionResult Index()
{
return View();
}
}
Action Result Types

Actions can return different types of results:

01 02 03

ViewResult ContentResult RedirectToAction-


Result

04 05

RedirectToRoute- StatusCodeResult
Result
Return a ContentResult Object

An action that returns a ContentResult:

public class AnotherController : Controller


{
public ContentResult AnotherAction()
{
return Content("some text");
}
}
Using Parameters

• The model binders obtain parameters from a user

request and pass them to action methods

• There are several ways to retrieve parameters,


including:

• The Request property

• The FormCollection object

• Routing
Using ViewBag and ViewData to Pass Information
to Views

• Models are the best way to pass data from controllers to views

• In some cases, you may want to augment the model with additional data

without modifying it
Using the ViewBag Property

• Adding Information:

ViewBag.Message = “some text”;


ViewBag.ServerTime = DateTime.Now;

• Retrieving Information:

<p>
Message is: @ViewBag.Message
</p>
<p>
Server time is: @ViewBag.ServerTime.ToString()
</p>
Demonstration: How to Write Controllers and Actions

In this demonstration, you will learn how to:

• Add a controller to an MVC application

• Add an action that creates a model and passes


it to a view

• Add another action that gets a parameter

• Add another action that returns a


ContentResult object

• Use the RouteData.Values collection to access


the action method data

• Use the ViewBag and ViewData properties to


pass data from a controller to a view
Lesson 2: Configuring Routes

01 02 03 04
The ASP.NET Discussion: What Is Search Configuring
Core Routing Why Add Engine Routes by Using
Engine Routes? Optimization? Convention-
Based Routing

05 06 07
Using Routes to Configuring Demonstration:
Pass Parameters Routes by Using How to Add
Attributes Routes
The ASP.NET Core Routing Engine

• Routing determines which controller and action should be called to handle a request

• Routing can be configured centrally in the Startup.cs file and locally by using attributes
Discussion: Why Add Routes?

Why add routes?

• To make URLs easier for site visitors to understand

• To improve search engine rankings


What Is Search Engine Optimization?

• Most users find web applications by using search engines

• It is important to ensure that your web application appears at the top of the search

engine results
Configuring Routes by Using Convention-
Based Routing
• Convention-based routes might contain the following properties: name, template,
defaults, constraints and dataTokens
• Custom routes can be added as shown below:

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{param}",
defaults: new { controller = "Some", action =
"ShowParam" },
constraints: new { param = "[0-9]+" });
});

• Routes should be added in the appropriate order


Using Routes to Pass Parameters

You can access the values of segment variables by using one of two methods:

• Using the RouteData.Values collection

public IActionResult Print()


{
string id = (string)RouteData.Values["id"];
return Content("id: " + id);
}

• Using model binding to pass appropriate parameters to actions

public IActionResult Print(string id)


{
return Content("id: " + id);
}
Configuring Routes by Using Attributes

• Attribute-based routing allows you to configure routes using attributes

• It allows you to define your routes in the same file as the controller that they refer to

[Route("Some")]
public IActionResult SomeMethod()
{
return Content("Some method");
}

• Convention-based routing and attribute-based routing can be used in the same application
Demonstration: How to Add Routes

In this demonstration, you will learn how to:

• Add convention-based routes to an MVC

application

• Add attribute-based routes to actions

• Add an attribute-based route with Http[Verb]

attribute
Lesson 3: Writing Action Filters

01 02 03
What Are Action Creating and Demonstration
Filters? Using Action : How to
Filters Create and Use
Action Filters
What Are Action Filters?

• Filters are MVC classes that can be used to manage cross-cutting concerns in your

web application

Authorization Logging Caching

• You can apply a filter to an action by annotating the action method with an
appropriate attribute
Filter Types

Authorization Resource Filters Model Binding Action Filters


Filters

Action Execution
Action Result
Conversion

Result Execution Result Filters Exception Filters


Creating and Using Action Filters

Sample Action Filter

public class SimpleActionFilter : ActionFilterAttribute {

public override void OnActionExecuting


(ActionExecutingContext filterContext) {

Debug.WriteLine("This Event Fired: OnActionExecuting");

public override void OnActionExecuted


(ActionExecutedContext filterContext) {

Debug.WriteLine("This Event Fired: OnActionExecuted");

}
Demonstration: How to Create and Use Action Filters

In this demonstration, you will learn how to:

• Add a filter to an MVC application

• Annotate an action with a filter


Module 3 Lab: Developing
Controllers
Labs And Exercises
Module Review
and Takeaways
Module 04
Developing View

83
Module Overview

Using HTML Helpers


01
Creating Views with
Razor Syntax 02 and Tag Helpers

03 Reusing Code in Views


Lesson 1: Creating Views with Razor Syntax

01 02 03
Adding Views Differentiating Features of the
Server-Side Code Razor Syntax
from HTML

06
04 05 Dependency
Demonstration: Alternative View Injection into
How to Use the Engines Views
Razor Syntax
Adding Views

• Views handle the presentation logic


• View files have a .cshtml extension
• Within a controller, you can use the View method

public class ProductController : Controller


{
public IActionResult Index()
{
return View();
}
}
Differentiating Server-Side Code from HTML

• Razor identifies server-side code by looking for the @ symbol


• Razor distinguishes the server-side code from the HTML content that is sent to
the browser unchanged

<body>
@for (int i = 0; i < 5; i++)
{
<span>@i</span>
}
</body>
Using the @ Symbol

In Razor syntax, the @ symbol has various uses.

You can:

Use @ to identify server-side Use @@ to render an @


C# code symbol in an HTML page

Use @: to explicitly declare Use <text> to explicitly


a line of text as content and declare several lines of text
not code as content and not code
Features of the Razor Syntax

A sample code block displaying the features of Razor

@* Some more Razor examples *@


<span>
Price including Sale Tax: @ViewBag.Price * 1.2
</span>
<span>
Price including Sale Tax: @(ViewBag.Price * 1.2)
</span>
@{
int i = 5;
int j = 6;
int z = i + j;
@z
}
Demonstration: How to Use the Razor Syntax

In this demonstration, you will learn how to:

• Add a view to an MVC application

• Add code to the view by using the Razor


syntax

• Use Razor to read a value from the ViewBag


property and render it to the browser
Alternative View Engines

• A view engine is a component of the MVC framework that is responsible for:


• Locating view files
• Running the server-side code that view files contain
• Rendering HTML that the browser can display to the user

• Razor is the default view engine in MVC

• It is possible to create a custom view engine


• Need to implement the IViewEngine interface
Dependency Injection into Views

• ASP.NET Core supports dependency injection into views

• You can inject a service into a view using the @inject directive

@inject <type> <instance name>


When Injecting Services into Views

Services to inject into views:


• Services that transform or format text
• Services that impact visual appearance
• Services that are required for many repeated uses inside a view

Services to inject into controllers:


• Services that retrieve data
• Services that depend on external resources
• Services that return consistent results for one view
Lesson 2: Using HTML Helpers and Tag Helpers

01 02 03 04 05
Introduction to Using HTML Action Demonstration: Using Tag Helpers Demonstration:
HTML Helpers and Helpers How to Use How to Use Tag
Tag Helpers HTML Helpers Helpers
Introduction to HTML Helpers and Tag Helpers

HTML helpers:
• Use a Razor syntax
• Make it easier to identify areas of code
• Does not require explicit enabling of the feature

Tag helpers:
• Use an HTML-like syntax, as well as tag properties
• Require explicit usage of a directive
• Create more easily legible HTML with less immediately apparent code
Using HTML Action Helpers

Html.ActionLink()

@Html.ActionLink("Click here to view photo 1",


"Display", new { id = 1 })

<a href="/photo/display/1">
Click here to view photo 1
</a>

Url.Action()
<img alt="This image came from an action"
src="@Url.Action("GetImage", new { id = 1 })" />

<img
alt="This image came from an action"
src="/photo/getimage/1" })"
/>
Demonstration: How to Use HTML Helpers

In this demonstration, you will learn how to:

• Use the Html.ActionLink helper to navigate


from one action to another action

• Use the Html.ActionLink helper to pass a


parameter to an action

• Use the Url.Action helper to generate a path to


an action
Using Tag Helpers

• Tag helpers are an alternative to HTML helpers


• Tag helpers look like regular HTML elements
• The following HTML helper and tag helper produce the same HTML:

HTML helper:

@Html.ActionLink("Press me", "AnotherAction")

Tag helper:

<a asp-action="AnotherAction">Press me</a>


Using the @addTagHelper Directive

• To use tag helpers, you need to add the @addTagHelper directive to a view

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

• To make tag helper available to all views, add the @addTagHelper directive
to the _ViewImports.cshtml file
Demonstration: How to Use Tag Helpers

In this demonstration, you will learn how to:

• Use the anchor tag helper to navigate from


one action to another action

• Pass a parameter to an action by using the


anchor tag helper

• Make tag helpers available to views by using


the _ViewImports.cshtml file
Lesson 2: Configuring Routes

01 02 03 04
Creating Partial Using Partial Demonstration: Creating View
Views Views How to Create Components
and Use Partial
Views

05 06 07
Using View Invoking View Demonstration:
Components Components with How to Create and
Parameters Use View
Components
Creating Partial Views

• Use partial views to render identical HTML content in different locations of your web
application
• Often created inside the /Views/Shared folder
• By convention, the names of partial views are prefixed with an underscore

For example:

_MyPartialView.cshtml

<p>In partial view</p>


Using Partial Views

You can use the Html.PartialAsync() method to render a


partial view within another view file

@await Html.PartialAsync("_MyPartialView")
Now in main view
@await Html.PartialAsync("_MyPartialView")

In partial view
Now in main view
In partial view
Demonstration: How to Create and Use Partial Views

In this demonstration, you will learn how to:

• Add a partial view to an MVC application

• Fill the content of the partial view

• Embed a partial view in a view by using the


Html.PartialAsync method
Creating View Components

• You can use view components to render identical or similar HTML content in different

locations

• A view component consists of two parts:

• A class

• Should be public and non-abstract

• Usually derived from the ViewComponent base class

• Should have a method called InvokeAsync, which defines its logic

• A view

• Can be located in a folder under Views\Shared\Components folder

• The name of the folder should be the same as the name of the view component class
without the ViewComponent suffix
A View Component Example

Content of a view component class located in a file named MyViewComponent.cs:

public class MyViewComponent : ViewComponent


{
public Task<IViewComponentResult> InvokeAsync()
{
return Task.FromResult<IViewComponentResult>(View("Default"));
}
}

Content of a view component view located in a file named Default.cshtml:

some text
Using View Components

You can include a view component in a view by:

using the @Component.InvokeAsync method:

@await Component.InvokeAsync("My")

some text

using a tag helper:

<vc:My></vc:My>

some text
Invoking View Components with Parameters

A view component that gets a parameter:

public async Task<IViewComponentResult> InvokeAsync(int param)


{
int id = await SomeOperationAsync(param);
return View("Default", id);
}

Pass a parameter to the view component:

@await Component.InvokeAsync("My", 5)
Demonstration: How to Add View Component

In this demonstration, you will learn how to:

• Add a view component class to an MVC


application

• Add a view component view to an MVC


application

• Embed the view component in a view


Module 4 Lab: Developing Views
Labs And Exercises
Module Review
and Takeaways
Module 05
Developing Models

112
Module Overview

01 Creating MVC Models 02 Working with Forms

Validating MVC
03 Application
Lesson 1: Creating MVC Models

01 02 03
Developing Passing Models Binding Views to
Models to Views Model Classes
and Displaying
Data

06
04 05 Adding CRUD
Demonstration: What Are Model Operations to
How to Bind Binders? Controllers
Views to Model
Classes
Developing Models

An MVC model is a collection of classes


The Photo and Comment Model Classes

public class Photo {


public int PhotoID { get; set; }
public string Title { get; set; }
public byte[] PhotoFile { get; set; }
public string Description { get; set; }
public DateTime CreatedDate { get; set; }
public string Owner { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}

public class Comment {


public int CommentID { get; set; }
public int PhotoID { get; set; }
public string UserName { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public virtual Photo Photo { get; set; }
}
Passing Models to Views

The instances of model classes are usually created in a controller and passed to a view
Passing a Model to the Display View

A sample code block displaying how to pass a model to a view.

public IActionResult Index()


{
SomeModel model = new SomeModel()
{ Text = "some text" };
return View(“Display”, model);
}
Binding Views to Model Classes and Displaying
Data

public class Person


{
public string FirstName { get; set; }
public string LastName { get; set; }
}

@EditorForModel
Demonstration: How to Bind Views to Model Classes

In this demonstration, you will learn how to:

• Add a model to an MVC application

• Pass a model from actions to views

• Render the model properties from the view to the


browser using @Model.PropertyName

• Render the model properties from the view to the


browser using @html.EditorForModel
What Are Model Binders?

• The ASP.NET Core MVC runtime uses model binders to determine


how parameters are passed to actions

• The default model binder passes parameters by using the following

logic:

• The binder examines the definition of the action that it must pass
parameters to

• The binder searches for values in the request that can be passed
as parameters
Passing Parameters to Actions

Person
FirstName=James
LastName=Smith

[HttpPost]
public IActionResult GetName(Person person)
Adding CRUD Operations to Controllers

A controller might be associated with CRUD operations:

• Create operations: Used to create or add new items

• Read operations: Used to read, retrieve, search or view


exiting entries

• Update operations: Used to update or edit existing entries

• Delete operations: Used to delete existing entries


Lesson 2: Working with Forms

01 02 03
Using Display and Using Display Using Editor
Edit Data Helpers Helpers
Annotations

04 05
Using Form Helpers Demonstration:
How to Use Display
and Edit Data
Annotations
Using Display and Edit Data Annotations

public class Person


{
[Display(Name="My Name")]
public string Name { get; set; }

[DataType(DataType.MultilineText)]
public string Description { get; set; }
}

@EditorForModel
Using Display Helpers

• Html.DisplayNameFor()

@Html.DisplayNameFor(model => model.FirstName)

First Name:

• Html.DisplayFor()

@Html.DisplayFor(model => model.FirstName)

James
Using Editor Helpers

• Html.LabelFor()

@Html.LabelFor(model => model.ContactMe)

<label for="ContactMe">
Contact Me
</label>

• Html.EditorFor()

@Html.EditorFor(model => model.ContactMe)

<input type="checkbox"
name="ContactMe" />
Using Editor Helpers (Continued)

• LabelTagHelper

<label asp-for="ContactMe"></label>

<label for="ContactMe">
Contact Me
</label>

• InputTagHelper

<input asp-for="ContactMe" />

<input type="checkbox"
name="ContactMe" />
Using Form Helpers

Html.BeginForm
@using (Html.BeginForm("ShowDetails",
"Person"))
{
}

<form
action="/Person/ShowDetails"
method="post“>
</form>

FormTagHelper

<form asp-controller="Person"
asp-action="ShowDetails">
</form>
Demonstration: How to Use Display and Edit Data
Annotations

In this demonstration, you will learn how to:

• Add data annotations to a model

• Build a form in the view by using form helpers

• Render the properties from the view to the


browser by using editor helpers

• Render the properties from the view to the


browser by using display helpers
Lesson 3: Validating MVC Application

01 02 03
Validating User Using Validation Demonstration:
Input with Data Helpers How to Validate
Annotations User Input with
Data Annotations

04 05
Adding Custom Demonstration:
Validations How to Add
Custom Validations
Validating User Input with Data Annotations

public class Person


{
[Required(ErrorMessage = "Please enter a name.")]
public string Name { get; set; }

[Range(0, 150)]
public int Age { get; set; }

[Required]
[RegularExpression(".+\\@.+\\..+")]
public string EmailAddress { get; set; }

[DataType(DataType.MultilineText)]
[StringLength(20)]
public string Description { get; set; }
}
Using Validation Helpers

• Html.ValidationSummary()

@Html.ValidationSummary()

<ul>
<li>Please enter a name.</li>
<li>The EmailAddress field is required</li>
</ul>

• Html.ValidationMessageFor()

@Html.ValidationMessageFor(model => model.Name)

Please enter a name.


Using Validation Helpers (Continued)

• ValidationSummaryTagHelper

<div asp-validation-summary=“All”></div>

<ul>
<li>Please enter a name.</li>
<li>The EmailAddress field is required</li>
</ul>

• ValidationMessageTagHelper

<span asp-validation-for=“Name”></span>

Please enter a name.


Demonstration: How to Validate User Input with Data
Annotations

In this demonstration, you will learn how to:

• Add validation data annotations to a model

• Use the ModelState.IsValid property in a


controller

• Use validation helpers in a view


Adding Custom Validations

• Create custom validation data annotations

public class AllLettersValidationAttribute :


ValidationAttribute
{
public override bool IsValid(Object value)
{
return ((string)value).All(Char.IsLetter);
}
}

• Use custom validation data annotations

[AllLettersValidation(ErrorMessage = "Only letters allowed.")]


public string Name { get; set; }
Demonstration: How to Add Custom Validations

In this demonstration, you will learn how to add


custom validations
Module 5 Lab: Developing Models
Labs And Exercises
Module Review
and Takeaways
Module 06
Using Entity Framework Core in ASP.NET Core

140
Module Overview

Working with Entity


01
Introduction to Entity
Framework Core 02 Framework Core

Using Entity Framework


03 Core to Connect to
Microsoft SQL Server
Lesson 1: Introduction to Entity Framework Core

01 02 03
Connecting to a Object Relational Overview of Entity
Database Using Mapper (ORM) Framework
ADO.NET

04 05
Discussion: Choose Database Providers
between Entity
Framework Core
and Entity
Framework 6
Connecting to a Database Using ADO.NET

• ADO.NET is a basic data access API that contains a


set of data providers

• Data providers connect to various databases

• ADO.NET providers consist of:

• Connection. Manages a connection to a database.

• Command. Represents a query or manipulation


operation.

• DataReader. Forward-only, cursor interface for


queries.

• DataAdapter. Tabular interface for queries.


ADO.NET Example

public class HomeController : Controller


{
public IActionResult Index()
{
string connectionString =
"Data Source=.\SQLEXPRESS;Initial Catalog=PhotoSharingDB;" +
"Integrated Security=SSPI";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
// Query or update the database
}

return View();
}
}
Object Relational Mapper (ORM)

• ORM is an approach designed to simplify the interaction with data

• There are multiple ORM frameworks

• Entity Framework is an ORM framework that was created for .NET

• ORM maps the tabular structure into data model classes

• You can use an ORM framework to modify objects in a database


Overview of Entity Framework

• Entity Framework provides a one-stop solution to interact


with data that is stored in a database

• Entity Framework Approaches:

• Database First

• Model First

• Code First

• Entity Framework Versions:

• Entity Framework 6 (EF6)

• Entity Framework Core (EF Core)


Discussion
Choose between Entity Framework Core
and Entity Framework 6

Which Entity Framework version will you use in the following scenarios?

(Choose one of the following in each scenario: Entity Framework 6, Entity


Framework Core)

• Working with a non-Windows environment

• Developing by using the Database First approach

• Creating a UWP application with a NoSql database


Database Providers

Application
Request sent to Response from
database provider database provider
with application with application
language language

Database Provider
Request sent to Response from
database with the the database with
database database
language language

Database
Lesson 2: Working with Entity Framework Core

01 02 03
Using an Entity Using LINQ to Loading Related
Framework Entities Data
Context

04 05
Manipulating Demonstration:
Data by Using How to Use
Entity Entity
Framework Framework Core
Using an Entity Framework Context

An entity:

public class Person


{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}

Entity Framework context:

public class HrContext : DbContext


{
public HrContext(DbContextOptions<HrContext> options) : base(options)
{
}
public DbSet<Person> Candidates{ get; set; }
}
Using an Entity Framework Context in Controllers

Using an Entity Framework Context in a Controller

public class HrController : Controller


{
private HrContext _context;
public HrController(HrContext context)
{
_context = context;
}
public IActionResult Index()
{
return View(_context.Candidates.ToList());
}
}
Using LINQ to Entities

• LINQ to Entities is the version of LINQ that works with Entity Framework

• Sample LINQ Query:

var list = from c in _context.Candidates


where c.LastName == "Smith"
select c;
Loading Related Data

• In Entity Framework Core you can load related entities

by using navigation properties

• To load related data, you need choose an ORM pattern

• Entity Framework Core contains several ORM patterns,

which include:

• Explicit loading

• Eager loading

• Lazy loading
Loading Related Data by using Explicit Loading

public IActionResult Index()


{
var city = _context.Cities
.Single(c => c.CityId == 1);

_context.Entry(city)
.Collection(c => c.People)
.Load();

_context.Entry(city)
.Reference(c => c.Country)
.Load();

return View(city);
}
Loading Related Data by using Eager Loading

public IActionResult Index()


{
var countries = _context.Countries
.Include(country => country.Cities)
.ThenInclude(city => city.People)
.ToList();

return View(countries);
}
Loading Related Data by using Lazy Loading

Navigation properties should to be overridden

public class Country


{
public virtual ICollection<City> Cities { get; set; }
}

Turn on the creation of lazy-loading proxies

services.AddDbContext<DemographyContext>(
options => options.UseLazyLoadingProxies()
.UseSqlite("Data Source=example.db"));
Manipulating Data by Using Entity Framework

• Entity Framework can track your entity changes

• The context uses in-memory snapshots to detect changes

• Call the SaveChanges method to save changes to the database

_context.People.Remove(person);

_context.SaveChanges();
Demonstration: How to Use Entity Framework Core

In this demonstration, you will learn how to:

• Add an Entity Framework context to an MVC


application

• Connect an Entity Framework context to a


SQLite database

• Use an Entity Framework context in a


controller

• Manipulate data by using Entity Framework


Core
Lesson 3: Using Entity Framework Core to Connect to
Microsoft SQL Server

01 02 03
Connecting to Configuration in Specifying a
Microsoft SQL ASP.NET Core Connection
Server String in a
Configuration File

04 05 06
The Repository Demonstration: Using Migrations
Pattern How to Apply the
Repository
Pattern
Connecting to Microsoft SQL Server

The UseSqlServer method configures the Entity Framework context to connect to a SQL
Server database

public void ConfigureServices(IServiceCollection services)


{
string connectionString = …;
services.AddDbContext<HrContext>(
options => options.UseSqlServer(connectionString));
services.AddMvc();
}
Configuration in ASP.NET Core

• Configuration is stored in name-value pairs

• Configuration can be read from multiple sources

• To read data from a source, use a configuration provider

• Configuration providers exist for:

• Files in JSON, XML and INI formats

• Environment variables

• Command line arguments

• Custom provider

• And more…
Specifying a Connection String in a
Configuration File
• Connection string in a configuration file:

{
"ConnectionStrings": {
"DefaultConnection": "..."
}
}

• Reading the connection string from the configuration file:

string connectionString =
_configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<HrContext>(options =>
options.UseSqlServer(connectionString));
The Repository Pattern
Demonstration: How to Apply the Repository Pattern

In this demonstration, you will learn how to:

• Write a repository interface

• Write a repository class

• Use a configuration file to store a


connection string

• Use dependency injection to inject a

repository to a controller

• Use a repository in a controller to access a


database
Using Migrations

• Migrations enable applying schema changes to the

database

• You can work with migrations by using the Entity


Framework Core Package Manager Console (PMC) Tools

• Fundamental migration commands

• Add a migration:

• Add-Migration <name_of_the_migration>

• Apply the migration to the database:

• Update-Database
Module 6 Lab: Using Entity
Framework Core in ASP.NET Core
Labs And Exercises
Module Review
and Takeaways
Module 07
Using Layouts, CSS and JavaScript in ASP.NET
Core MVC

169
Module Overview

Using CSS and


01
Using Layouts
02 JavaScript

03 Using jQuery
Lesson 1: Using Layouts

01 02 03
What are Layouts? Creating a Layout Linking Views and
Layouts

04 05
Using Sections in a Demonstration:
Layout How to Create a
Layout and Link it
to a View
What are Layouts?

You can use layouts to:

• Create a style template for a web application

• Define the content layout to share across all views

Layout

View View View


Creating a Layout

When you create a layout:

• You should store the layout files in the

\Views\Shared folder

• You can use the @RenderBody method to place

the content of a view in the layout

• You can use the ViewBag property to pass


information between a view and the layout
A Layout Example

An example of a layout:

<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
</head>
<body>
<div>
@RenderBody()
</div>
</body>
</html>
Linking Views and Layouts

To link views and layouts:

• You can add the Layout directive at the top of the view file

• You can use the _ViewStart.cshtml file to define the layout


• Add the _ViewStart.cshtml file to the \Views folder of your project
Using Sections in a Layout

• Use the @RenderSection method in a layout

@RenderSection("section1")
@RenderBody()
@RenderSection("section2", false)

• Use the @section directive in a view

@section section1
{
<div>This is section1 content</div>
}
<div>This is the body</div>
Demonstration: How to Create a Layout and Link it to
a View

In this demonstration, you will learn how to:

• Add a _ViewStart.cshtml file to an MVC application

• Add a layout to an MVC application

• Use the @RenderBody method in the layout

• Use the @RenderSection method in the layout

• Link views and a layout


Lesson 2: Using CSS and JavaScript

01 02 03 04
Importing Styles Rendering and Using External Demonstration:
Executing Libraries How to Use npm to
JavaScript Code Add a Library
Importing Styles

• After importing the CSS file:

• You should modify the layout of the web application by using the <link>
element

• You can add CSS selectors to define how the styles should be applied:

• CSS class selector helps specify a style for a group of elements

• CSS id selector helps specify a style for any unique element in the
HTML code

.menu
{
font-weight:bold; <p class="menu"> this is menu</p>
}
Rendering and Executing JavaScript Code

• You can add JavaScript code to add interactive functionalities to webpages

<script>
function helloWorld() {
alert('Hello World');
}
</script>

• You can add JavaScript code to web applications by:


Adding the JavaScript code to a view
• Defining the JavaScript code in dedicated JavaScript files
Calling JavaScript Functions

• You can call JavaScript functions by using script blocks:


• Define the JavaScript function in a script block

<script>

helloWorld()

</script>

• You can also use events to trigger JavaScript functions:


• Use the onclick event to initiate the JavaScript function

<input type="button" value="Hello" onclick="helloWorld();" />


Using External Libraries

To add a library to your application, you can:

Use a Package
Download the Use a CDN Manager
source files (Content • NuGet – For
from an Delivery server-side
official source Network) libraries
• Yarn
• Webpack
• Bower
• npm
Using npm to Add Libraries

To start using NPM in an ASP.NET Core application, you should add a package.json file to your solution in
your project’s root folder:

{
"version": "1.0.0",
"name": "asp.net",
"private": true,
"dependencies": {
"jquery": "3.3.1"
},
"devDependencies": {

}
}
Demonstration: How to Use npm to Add a Library

In this demonstration, you will learn how to:

• Add the jQuery package by using npm

• Add a link to a jQuery file from a layout

• Add a CSS file

• Add a link to the CSS file from a layout


Lesson 3: Using jQuery

01 02 03
Introduction to Accessing HTML Modifying HTML
jQuery Elements by using Elements by using
jQuery jQuery

04 05 06
Demonstration: Calling a Server by Client-Side
How to Modify using jQuery Validation by using
HTML Elements by jQuery
using jQuery
Introduction to jQuery

• jQuery is a cross-browser JavaScript library

• Benefits of using jQuery:

• It reduces the amount of code that you need to write

• It reduces the application development time

• jQuery files:

• jQuery original version:

• Is the uncompressed version of jQuery

• Is optimized for development and debugging

• jQuery minified version:

• Is the compressed version of jQuery

• Is optimized for production


jQuery Syntax

Every jQuery line of code starts with the $ or jQuery variables

$(function() {
$.each([4, 9], function(index, value) {
alert(index + ":" + value);
});
});
Accessing HTML Elements by using jQuery
• You can use the following selector to select elements by element name, id,
or CSS class:

$(element name|#id|.class)

• After accessing the HTML elements:

• Modify the attributes on the elements

• Define event handlers to respond to events

$("#hello").click(function(event) {
alert("Hello World");
});
Modifying HTML Elements by using jQuery

• jQuery functions include:

• The val function:

• Allows to get or set the value of an HTML element

• The css function:

• Allows to get or set the inline CSS style associated with an


HTML element

• The addClass function:

• Assigns the CSS class to an HTML element

• The animate function:

• Creates transition between CSS properties assigned to an HTML


element
Demonstration: How to Modify HTML Elements by
using jQuery

In this demonstration, you will learn how to:

• Add a JavaScript file to an ASP.NET Core


application

• Use jQuery to read data from an HTML element

• Use jQuery to modify an HTML element

• Add a link to a JavaScript file from a layout


Calling a Server by using jQuery

The ajax function:

• Helps perform calls to a server

• Includes parameters such as type, url, data, and contentType

• Helps obtain the data returned from a server

• Uses callback functions to derive the results of the server calls


Client-Side Validation by using jQuery

Advantages of client-side validation:

• Immediate validation

• No need to wait for a server response

• Better user experience

Disadvantages of client-side validation:

• Less secure

• Easy to bypass

• The best practice in MVC applications is to have both

server and client validation


Adding Client-Side Validations

• Insert the following libraries to a view:

• jQuery Validate. A jQuery plugin that makes


client-side form validations easy

• jQuery Unobtrusive Validation. Allows to use


the same validation logic you wrote on the server-
side also on the client-side

• Add asp-for attribute on form input elements needing

validation

• Add asp-validation-for attribute on HTML elements

that will display validation errors


Module 07 Lab: Using Layouts, CSS
and JavaScript in ASP.NET Core MVC
Labs And Tasks
Module Review
and Takeaways
Module 08
Client-Side Development

196
Module Overview

01 Applying Styles 02 Using Task Runners

03 Responsive Design
Lesson 1: Applying Styles

01 02 03
Introduction to Bootstrap Demonstration:
Bootstrap Components How to Work with
Bootstrap

04 05
Styling Applications Styling Applications
with Sass with Less
Introduction to Bootstrap

What is Boostrap?

• Bootstrap is a HTML, CSS and JS framework

for building responsive web applications

• Allows you to quickly develop the client-side

of your web applications

• Includes pre-built components and styles


Adding Bootstrap to a Web Application

To get started with bootstrap you need to add a few files to your application:

• bootstrap.css – Includes all the CSS that Bootstrap needs to work

• bootstrap.js – Includes all the JavaScript that Bootstrap needs to work

• jQuery – Boostrap is dependant on jQuery and needs it to work

• popper.js – This library is responsible for the HTML elements that pop out

of the natural flow of the page like tooltips

"dependencies": {
"bootstrap": "4.1.3",
"jquery": "3.3.1",
"popper.js": "1.14.3"
}
Bootstrap Components

• Bootstrap includes a large variety of pre-built

components, such as:

• Alerts, Buttons, Dropdowns, Nav menus,


Navbars, Modal windows and more

• To create these components, it is important to

follow the right HTML hierarchy that is described


inside the Bootstrap documentation and add all
needed CSS classes

• When a required class is missing or the

hierarchy is not right, the elements will not look


and behave as expected
Bootstrap Components Example

<div class="alert alert-danger">A designed alert message</div>

<button type="button" class="btn btn-secondary">Back</button>


<button type="button" class="btn btn-primary">Next</button>

<ul class="nav">
<li class=“nav-item”>
<a class="nav-link active" href=“/">Home</a>
</li>
<li class=“nav-item”>
<a class="nav-link" href=“/home/about">About</a>
</li>
</ul>
Demonstration: How to Work with Bootstrap

In this demonstration, you will learn how to:

• Add Bootstrap to your web application by


using npm

• Add Bootstrap components to your web


application
Styling Applications with Sass

• Sass is a language that is compiled to CSS

• Installing Sass by using npm:


• npm install -g sass

• Compiling Sass file:


• sass main.scss main.css
Exploring Sass

$highlights: #00FFFF;

.p {
color: $highlights;
font-size: 16px;
span {
color: darken($highlights, 20%);
em {
text-decoration: underline;
}
}
}
Styling Applications with Less

• Less is a language that is compiled to CSS

• Installing Less by using npm:


• npm install -g less

• Compiling a Less file:


• lessc main.less main.css
Exploring Less

@highlights: #00FFFF;

.p {
color: @highlights;
font-size: 16px;
span {
color: darken(@highlights, 20%);
em {
text-decoration: underline;
}
}
}
Lesson 2: Using Task Runners

01 02 03 04
Using Grunt Using gulp Demonstration: Bundling and
How to Use gulp to Minification
Compile Sass to
CSS
Using Grunt

• Grunt is a task runner

• Used to perform operations such as bundling, minification and

compilation

• Sections of Grunfile.js:

• Project and task configuration information

• Loading the grunt plugins and tasks

• Custom tasks that are created by the user


Grunt Example

module.exports = function(grunt) {
grunt.initConfig({
sass: {
dist: {
files: [{
expand: true,
cwd: 'Styles',
src: ['**/*.scss'],
dest: 'wwwroot/styles',
ext: '.css'
}]
}
}
});
grunt.loadNpmTasks("grunt-sass");
};
Using gulp

• gulp is a task runner

• A gulp task can perform several sequential operations on a single

pipeline

• Task configuration will be done inside a gulpfile.js file


gulp Example

var gulp = require('gulp');


var sass = require('gulp-sass');

var paths = {
webroot: "./wwwroot/"
};

paths.sass = "./Styles/*.scss";
paths.compiledCss = paths.webroot + "styles/";

gulp.task("sass", function() {
return gulp.src(paths.sass)
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest(paths.compiledCss));
});
Multiple Tasks in gulp

var gulp = require('gulp’);

gulp.task("one", function() {
console.log("one");
});
gulp.task("two", function() {
console.log("two");
});
gulp.task("three", function() {
console.log("three");
});

gulp.task("all", ["one", "two", "three"], function() {


console.log("four");
});
Demonstration: How to Use gulp to Compile Sass to
CSS

In this demonstration, you will learn how to:

• Configure an ASP.NET Core Web


Application to use gulp

• Add a Sass file to an ASP.NET Core Web


Application

• Use gulp to Compile the Sass file to a


CSS file
Bundling and Minification

• One of the most frequent usages of task runners is to perform bundling

and minification

• Bundling. Reduces the number of files

• Minification. Reduces the size of files

• To perform bundling and minification, the following gulp plugins can be

added:

• gulp-concat. Used for combining multiple files performing a bundling


operation

• gulp-cssmin. Minifies the CSS files

• gulp-uglify. Minifies the JavaScript files


Bundling and Minification Example

gulp.task("minify-js", function() {

return gulp.src(paths.jsFiles)

.pipe(concat(paths.minifiedJsFileName))

.pipe(uglify())

.pipe(gulp.dest(paths.destinationJsFolder));

});

gulp.task("js-watcher", function() {

gulp.watch(paths.jsFiles, ["minify-js"]);

});
Lesson 3: Responsive Design

01 02 03
The HTML5 CSS Media Queries The Bootstrap Grid
Viewport Attribute System

04 05
Demonstration: Applying the
How to Use the Flexbox Layout
Bootstrap Grid
System
The HTML5 Viewport Attribute

The viewport attribute helps render webpages in a virtual window in mobile devices

<meta name="viewport" content="width=device-


width,
initial-scale=1, maximum-scale=1">
CSS Media Queries

Characteristics of media queries:


• Media queries are special selectors that begin with @media
• You can also apply media queries in the <link> elements
• Media queries support properties that allow you to specify the size details
of the targeted display area

@media only screen and (max-width: 500px) {


header{
float: none;
}
}
The Bootstrap Grid System

• Bootstrap grid is a layout system which includes 12 columns


• It uses containers, rows and columns to organize and align the content

<div class="container">
<div class="row">
<div class="col">
<h3>First Column</h3>
</div>
<div class="col">
<h3>Second Column</h3>
</div>
</div>
</div>
Demonstration: How to Use the Bootstrap Grid
System

In this demonstration, you will learn how to:

• Configure an ASP.NET Core web


application to use Bootstrap

• Use the Bootstrap grid system

• Use alignment in the grid


Applying the Flexbox Layout

• All modern browsers support Flexbox

• It provides an efficient way to layout and align items inside a specific parent

container

• Using display: flex a parent container can alter its children items width, height

and order to fill the available space within it

• Each direct child inside the flex container can override the behavior specified by

the parent container

Parent container

Child item
Using Flexbox

.container {
display: flex; <div class="container">
justify-content: center; <div class="box box-1">01</div>
align-items: center; <div class="box box-2">02</div>
<div class="box box-3">03</div>
height: 800px;
background-color: gray; <div class="box box-4">04</div>
padding: 20px; </div>
}
.box {
width: 100px;
}
.box-4 {
order: -1;
align-self: flex-start;
}
.box-2 {
flex-grow: 2;
}
Module 08 Lab: Client-
Side Development
Labs and Tasks
Module Review
and Takeaways
Module 9
Testing and Troubleshooting
Module Overview

Implementing an
01 Testing MVC Applications 02 Exception Handling
Strategy

03 Logging MVC Applications


Lesson 1: Testing MVC Applications

01 02 03
Why Perform Unit Principles of Test- Writing Loosely
Tests? Driven Coupled MVC
Development Components

04 05 06
Writing Unit Tests Demonstration: Using Mocking
for MVC How to Run Unit Frameworks
Components Tests
Why Perform Unit Tests?

• Types of Tests:

• Unit tests

• Integration tests

• Acceptance tests

• Unit tests verify that small units of functionality work as designed

• Arrange. This phase of a unit test arranges data to run the test on

• Act. This phase of the unit test calls the methods you want to test

• Assert. This phase of the unit test checks that the results are as
expected

• Any unit test that fails is highlighted in Visual Studio whenever you
run the test or debug the application

• Once defined, unit tests run throughout development and highlight


any changes that cause them to fail
Principles of Test-Driven Development

Write the Test

▪ Understand the
problem
▪ Specify the
desired
behavior
▪ Run the test
▪ Test fails

Refactor Pass the Test

▪ Clean the code


and remove ▪ Write application
assumptions code
▪ Test passes ▪ Run the test
▪ Test passes
Writing Loosely Coupled MVC Components

• Loose coupling means that each component in a


system requires few or no internal details of the
other components in the system

• A loosely coupled application is easy to test because

it is easier to replace a fully functional instance of a


class with a simplified instance that is specifically
designed for the test

• Loose coupling makes it easier to replace simple

components with more sophisticated components

• Dependency injection inherently supports loose

coupling
Writing Unit Tests for MVC Components

• You can test an ASP.NET Core MVC web

01
application project by adding a test
project to the solution

• Model classes can be tested by


instantiating them in-memory, arranging
01 their property values, acting on them by
calling a method, and asserting that the
result was as expected
Testing a Controller

You can test a controller by:

01 Creating a repository service

02 Implementing and using a repository in the application

03 Implementing a test double repository

04 Using a test double to test a controller


Using a Test Double in a Unit Test

[TestMethod]
public void IndexModelShouldBeListOfProducts()
{
// Arrange
var productRepository = new FakeProductRepository();

productRepository.Products = new[] { new Product(), new Product(),


new Product() }.AsQueryable();

var productController = new ProductController(productRepository);

// Act
var result = productController.Index() as ViewResult;

// Assert
Assert.AreEqual(typeof(List<Product>), result.Model.GetType());
}
Demonstration: How to Run Unit Tests

In this demonstration, you will see how to:

• Add a new test project,


ProductsWebsite.Tests, to a solution to
test an ASP.NET Core MVC web application

• Create code for two unit tests

• Observe the results of the unit tests – one


of them fails and the other one passes

• Fix the code

• Observe the results of the unit tests – both


of them pass
Using Mocking Frameworks

• A mocking framework automates the creation of

mock objects during tests

• You can automate the creation of a single


object

• You can automate the creation of multiple


objects of the same type

• You can automate the creation of multiple


objects that implement different interfaces

• The mocking framework saves time when writing

unit tests
Lesson 2: Implementing an Exception
Handling Strategy

01 02 03 04
Raising and Working with Configuring Error Demonstration:
Catching Multiple Handling How to Configure
Exceptions Environments Exception Handling
Raising and Catching Exceptions

• The most common method to catch an exception is to use the try/catch block

• You can add custom exceptions or use existing ones

throw new ArgumentNullException();



try
{
price =
product.GetPriceWithTax(-20);
}
catch (InvalidTaxException ex)
{
return Content("Tax cannot be
negative");
}
Working with Multiple Environments

• Use the environment variable ASPNETCORE_ENVIRONMENT to


determine application environment

• The IHostingEnvironment interface exposes useful methods:

• IsDevelopment

• IsStaging

• IsProduction

• IsEnvironment(*Environment Name*)
Using Environments in Views

Use the environment tag helper to differentiate between environments inside views

<environment include="Development">
<script src="~/Scripts/jquery.js"></script>
<script src="~/Scripts/popper.js"></script>
<script src="~/Scripts/bootstrap.js"></script>
</environment>
<environment include="Production,Staging">
<script src="~/Scripts/vendor.min.js"></script>
</environment>
Configuring Error Handling

In ASP.NET Core applications, there are many ways to


handle errors including:

• Using the developer exception page

• Using an exception handler to direct to a custom


error page

• Using status code pages

• Using exception filters to catch exceptions in


specific actions and controllers
Configuring Error Handling Example

public void Configure(IApplicationBuilder app, IHostingEnvironment env)


{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else if (env.IsStaging() || env.IsProduction()))
{
app.UseExceptionHandler("/error");
}
app.UseMvcWithDefaultRoute();
app.UseStatusCodePages();
app.Run(async (context) =>
{
await Task.Run(() => context.Response.StatusCode = 404);
});
}
Demonstration: How to Configure Exception Handling

In this demonstration, you will see how to:

• Run an ASP.NET Core application in different


environments

• Handle errors in production by using the


UseExceptionHandler middleware

• Handle errors in development by using the


UseDeveloperExceptionPage middleware

• Locate and fix errors in the code by using the


developer exception page
Lesson 3: Logging MVC Applications

01 02 03
Logging Exceptions Logging in ASP.NET Demonstration:
Core How to Log an MVC
Application
Logging Exceptions

Live Web
Application

Administrator

Error
User

Database

When an exception occurs, the application sends an email message to the administrators,
and logs full details of the exception to a database.
Logging in ASP.NET Core

public IActionResult Index()


{
_logger.LogDebug("Index controller was entered");
try
{
int x = 3;
x -= 3;
int result = 30 / x;
}
catch (Exception ex)
{
_logger.LogError(ex, "An error occured while dividing!");
}
return Content(“Result from controller");
}
Demonstration: How to Log an MVC Application

In this demonstration, you will see how to:

• Configure logging of an ASP.NET Core


application

• Write log messages to a file and to the


console

• Investigate and solve problems in an


ASP.NET Core application using log
messages
Module 9 Lab: Testing and
Troubleshooting
Labs And Exercises
Module Review
and Takeaways
Module 06
Managing Security

250
Module Overview

Authorization in
01
Authentication in
ASP.NET Core 02 ASP.NET Core

03 Defending from Attacks


Lesson 1: Authentication in ASP.NET Core

01 02 03
The Need for Setting up Interfacing with
Authentication ASP.NET Core ASP.NET Core
Identity Identity

04 05 06
ASP.NET Core Demonstration: Customizing
Identity How to use Providers with
Configuration ASP.NET Core ASP.NET Core
Identity
The Need for Authentication

Why Authentication is Needed

To help prevent
To ensure malicious activities
connected users on your
use the correct application or
credentials website

To identify the To enable you to


users that are block sensitive
connected to your resources from
application or unauthenticated
website users
Authentication Methods

Single Factor Two Factor

OAuth Mobile Authentication


Authentication
methods

Biometrics API Authentication

Multi Factor
Setting up ASP.NET Core Identity

ASP.NET Core Identity requires some configurations to be specified before it can


be used:

01 02 03 04
It requires an It requires It requires a call It requires a call
Identity class IdentityDbConte to to
inheriting from xt which is used AddDefaultIdent UseAuthentication
IdentityUser for all database ity in in Configure
communications ConfigureServic
es
Program.cs Configurations for Adding Authentication

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.


var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ??
throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddDefaultIdentity<IdentityUser>(
options => options.SignIn.RequireConfirmedAccount = false
).AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddControllersWithViews();
ASP.NET Core Identity Configuration

There are many things you can configure in ASP.NET Core Identity configuration:

User settings –
01 Allow to configure what constitutes a legal username and other options

Lockout settings –
02 Allow to customize lockout behavior if incorrect passwords are supplied

Password settings –
03 Allow setting password complexity rules

Sign in settings –
04 Allow requiring additional methods of authentication before creating users

Cookie settings –
05 Allow changing the behavior of cookies on the website
Demonstration: How to use ASP.NET Core Identity

In this demonstration, you will learn how to


Configure ASP.NET Core Identity
Customizing Providers with ASP.NET Core

• By default, ASP.NET Core Identity uses Entity Framework and the built-in authentication
logic

• You can extend Identity to allow authentication from multiple external sources

• You are also able to use Windows Active Directory to handle authentication for you, to
prevent external users from accessing your application

• Furthermore, the backend can be fully customized to use any form of storage you require,
as long as it can be used in an ASP.NET Core application
Lesson 2: Authorization in ASP.NET Core

01 02 03
Introduction to Authorization Demonstration:
Authorization Options How to Authorize
Access to
Controller
Actions
Introduction to Authorization

The AuthorizeAttribute attribute:

• Restricts user access to information

• Mandates that users should be authorized to

access the authorized controller or action

The AllowAnonymousAttribute attribute:

• Allows users access to an action in a controller

with the Authorize attribute


Authorization Options

There are many different ways to block users from accessing resources.

You may want certain resources or actions only


available to administrative users and can
implement this by using roles

You might want users to provide specific


information before allowing them access to certain
resources and can implement this by using claims

You might want a completely unique logic for


directing access and can implement this by using
custom policies
Demonstration: How to Authorize Access to
Controller Actions

In this demonstration, you will see how to:

• Set up authorization

• Use simple authorization


Lesson 3: Defending from Attacks

01 02 03
Cross-Site Cross-Site SQL Injection
Scripting Request Forgery

04 05
Cross-Origin Secure Sockets
Requests Layer
Cross-Site Scripting

Cross-site scripting involves:

• Inserting malicious code in the session of a user

• Posting information to other websites without the

knowledge of the concerned users

You can prevent cross-site scripting by:

• Using the JavaScriptEncoder class and the Encode

method when encoding inputs into JavaScript

• Using the URLEncoder class and the Encode method

when encoding inputs into URL


Cross-Site Request Forgery

Cross-Site Request Forgery

• Exploits existing cookies on a browser to

perform actions on victim sites maliciously.

To prevent them in your ASP.NET Core MVC


applications you should do the following:

• Utilize ValidateAntiForgeryToken or

AutoValidateAntiForgeryToken to protect
actions on your controllers

• Use tag helpers and forms with PUT, POST or

DELETE methods in your views to ensure


tokens are created correctly
SQL Injection

SQL Injection Attack

To prevent this attack, you can:

Utilize Entity Framework Use parameterized Use stored procedures–


or other ORMs – queries– Stored procedures use
These libraries are designed These can allow you to
parameters, and do not
with SQL injection in mind, create dynamic SQL while
execute SQL that is not
and make it harder to preventing external sources
present inside the stored
perform from affecting it
procedure

Use the lowest required Review parameters–


permissions–
Restricting permissions Ensure that any parameter
added into SQL cannot be
granted to your application
can help prevent table used to run SQL code

modifications
Cross-Origin Requests

Cross-Origin Resource Sharing (CORS)

By default your server You can enable it and Enabling CORS can
will not accept any utilize CORS policies to create a risk within
cross-origin requests create conditions under applications and needs
from external sources. which your application to be handled with
content will be care. It is important to
accessible to external create policies as
applications. specific as required.
Secure Sockets Layer

SSL:

01 02 03 04
Encrypt Decrypt Ensure Certify

Encrypts content by Decrypts content by Ensures that data Certificate is


using the public key utilizing the private sent across the web determined on the
declared by the key only available to is encrypted, making initial request
certificate the certificate owner it much harder to between the client
steal or change and server

© 2023 elev8 - All rights reserved. 269


Module 10 Lab: Managing
Security
Labs And Exercises
Module Review
and Takeaways
Module 11
Performance and Communication
Module Overview

Implementing a
01 Caching Strategy in 02 Managing State
ASP.NET Core
Lesson 1: Implementing a Caching Strategy

01 02 03
Why Use Cache Tag Helper Demonstration:
Caching? How to Configure
Caching

04 05
The Data Cache Distributed
Cache
Why Use Caching?

Caching:

• Helps improve the performance of a web


application by reducing the time needed to
process a webpage

• Helps increase the scalability of a web


application by reducing the workload on the
server

• Can be customized to retain an appropriate


life time and priority for the data being
cached
Cache Tag Helper

• One way to cache in an ASP.NET Core MVC application is

by using the cache tag helper

• cache tag helper attributes:

• enabled

• priority

• Expiration attributes: expires-on, expires-after,


expires-sliding

• vary-by attributes: vary-by-query, vary-by-cookie,


vary-by-route, vary-by-user, vary-by-header, vary-by
Cache Tag Helper Example

<cache>
@for (int i = 0; i < DateTime.Now.Second; i++)
{
<div>Number of seconds</div>
}
</cache>

<cache vary-by="@Model.Id">
<div>
@Model.Name
</div>
<div>
@Model.Price
</div>
</cache>
Demonstration: How to Configure Caching

In this demonstration, you will see how to:

• Use a cache tag helper

• Use a vary-by attribute to create a


cache per loaded product
The Data Cache

To cache data, you can use the IMemoryCache


service

• Register the service in the ConfigureServices


method

• Inject the service throughout the components of


your application

• Use the Set method to store data in the cache

• Use the TryGetValue method to retrieve data


from the cache
Data Cache Example

public IActionResult Index()


{
List<Product> products;

if (!_memoryCache.TryGetValue(PRODUCT_KEY, out products))


{
products = _productService.GetProducts();
MemoryCacheEntryOptions options = new MemoryCacheEntryOptions();
options.SetPriority(CacheItemPriority.Low);
options.SetSlidingExpiration(new TimeSpan(6000));
_memoryCache.Set(PRODUCT_KEY, products, options);
}

return View(products);
}
Distributed Cache

Distributed cache:

• Stores shared cache data across multiple users and


servers

• Can be configured to work with both SQL and Redis

• Is managed by using the IDistributedCache interface to


cache information in components such as controllers

• Is managed by using a distributed-cache tag helper


alongside the name attribute in views
Lesson 2: Managing State

01 02 03
Why Store State State Storage Configuring
Information? Options Session State

04 05
Demonstration: Using the HTML5
How to Store and Web Storage API
Retrieve State
Information
Why Store State Information?

Using states:

• Creates a continuity between multiple different


requests

• Allows identifying specific users and using user


specific logic

• Is required for handling authentication

• Allows developers to overcome weaknesses of


using a stateless protocol
State Storage Options

State Storage:
• Allows websites to maintain a more coherent continuous
experience
• Involves client-side session management techniques
such as:
• Hidden fields
• Cookies
• Query strings
• Involves server-side session management techniques
such as:
• TempData
• HttpContext.Items
• Cache
• Dependency Injection
• Session state
TempData Example

public IActionResult Index()


{
object tempDataValue = TempData["myKey"];

if (tempDataValue != null)
{
return Content("TempData exists!" + tempDataValue);
}

TempData["myKey"] = "Temporary Value";


return Content("TempData does not exist!");
}
Configuring Session State

public IActionResult Index()


{
int? visitorCount = HttpContext.Session.GetInt32(VISIT_COUNT_KEY);
if (visitorCount.HasValue)
{
visitorCount++;
}
else
{
visitorCount = 1;
}
HttpContext.Session.SetInt32(VISIT_COUNT_KEY, visitorCount.Value);
return Content(string.Format("Number of visits:{0}", visitorCount));
}
Demonstration: How to Store and Retrieve State
Information

In this demonstration, you will see how to:

• Configure an ASP.NET Core application to


use session state

• Retrieve values from the


HttpContext.Session property

• Store values in the


HttpContext.Session property
Using the HTML5 Web Storage API

Types of storage:

• Local storage – Persists until removed and


is shared between tabs

• Session storage – Exists for a single tab


and removed when it is closed

Functions which exist in both local storage and


session storage:

• Get – Retrieves a stored value for a key

• Set – Stores a chosen value for a key

• Remove – Removes a saved value for a


key
Local Storage Example

var storage_key = "num_of_visits";


var numberOfVisitsString = localStorage.getItem(storage_key);
var numberOfVisits = 1;
if (numberOfVisitsString) {
numberOfVisits = parseInt(numberOfVisitsString) + 1;
}
alert("The page has been visited “ + numberOfVisits + " times");
if (numberOfVisits >= 5) {
localStorage.removeItem(storage_key);
} else {
localStorage.setItem(storage_key, numberOfVisits);
}
Module 11 Lab: Performance
and Communication
Labs and Tasks
Module Review
and Takeaways
Module 12
Implementing Web APIs
Module Overview

01 Introducing Web APIs 02 Developing a Web API

03 Calling a Web API


Lesson 1: Introducing Web APIs

01 02 03
HTTP Services HTTP Messages Status Codes

04 05
Introduction to What is a Web
Web API API?
HTTP Services

• HTTP is a first class application protocol

• An HTTP URI has the following basic structure:


http://blueyonder.com:8080/travelers?id=1

Schema Host Port Absolute Query


Path

• HTTP defines a set of methods or verbs that add action-


like semantics to requests
HTTP Services (Continued)

• REST is an architectural style that was developed in

parallel to HTTP

• REST is used to add important capabilities to a service

• Media types are used in HTTP to express message format

• Client and server need to agree on the message


format they exchange
HTTP Messages

An HTTP request message:

GET http://localhost:4392/travelers/1 HTTP/1.1

Accept: text/html, application/xhtml+xml, */*

Accept-Language: en-US,en;q=0.7,he;q=0.3

User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows


NT 6.2; WOW64; Trident/6.0)

Accept-Encoding: gzip, deflate

Host: localhost:4392

DNT: 1

Connection: Keep-Alive
An HTTP Response Message

An HTTP response message:

HTTP/1.1 200 OK
Server: ASP.NET Development Server/11.0.0.0
Date: Tue, 13 Nov 2012 18:05:11 GMT
X-AspNet-Version: 4.0.30319
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Content-Type: application/json; charset=utf-8
Content-Length: 188
Connection: Close

{"TravelerId":1,"TravelerUserIdentity":"aaabbbccc","
FirstName":“John","LastName":“Doe","MobilePhone":
"555-555-5555","HomeAddress":“123 Main
Street","Passport":"AB123456789"}
Status Codes

• Status codes describe the result of the server’s attempt


to process the request
• Status codes are constructed from a three-digit integer
and a description called reason phrases
• HTTP has five different categories of status codes:
• 1xx – Informational
• 2xx – Success
• 3xx – Redirection
• 4xx – Client Error
• 5xx – Server Error
Introduction to Web API

• For a long time the .NET Framework did not

have a first-class framework for building HTTP


services

• The need for developing HTTP services justified


creating a new framework

• In February 2012, ASP.NET Web API was


released

• In June 2016, ASP.NET Core Web API was

released
What is a Web API?

Web API:
• Helps create REST-style APIs

• Enables external systems to use the business logic implemented in your

application

• Uses URLs in requests and helps obtain results

• Is ideal for mobile application integration

Request

Response
Lesson 2: Developing a Web API

01 02 03 04
Using Routes and RESTful Services Action Methods Binding
Controllers and HTTP Verbs Parameters to
Request Message

05 06 07
Control the HTTP Data Return Demonstration:
Response Formats How to Develop
a Web API
Using Routes and Controllers

Obtaining information by using Web API:

[Route("api/[controller]")]
public class HomeController : ControllerBase
{
public string Get()
{
return "Response from Web API";
}
}
RESTful Services

Characteristics of a REST Service:

• Can be called to retrieve business information from the server

• Can create, update, and delete information in a database through HTTP


operations

• Uses URLs to uniquely identify the entity that it operates on

• Uses HTTP verbs to identify the operation that the application needs to
perform. The HTTP verbs include:

• GET

• POST

• PUT

• DELETE
A Rest Service Example

[Route("api/[controller]")]
public class CustomerController : ControllerBase
{
public IEnumerable<Customer> Get()
{}
public void Post(Customer item)
{}
public void Put(int id, Customer item)
{}
public void Delete(int id)
{}
}
Action Methods and HTTP Verbs

You can use the following attributes to control the


mapping of HTTP requests (HTTP verb+URL) to
actions in the controller:

• The HttpGet, HttpPut, HttpPost, or


HttpDelete attributes

• The AcceptVerbs attribute

• The ActionName attribute


Action Methods and HTTP Verbs Example

[Route("api/[controller]")]
public class HomeController : ControllerBase
{
[HttpGet("Some")]
public string SomeMethod()
{
return "SomeMethod was invoked";
}

[HttpGet("Other")]
public string OtherMethod()
{
return "OtherMethod was invoked";
}
}
Binding Parameters to Request Message

• An action that gets two parameters:

[Route("api/[controller]")]
public class HomeController : ControllerBase
{
[HttpGet("{id}/{name}")]
public string Get(int id, string name)
{
return "id: " + id + ", name: " + name;
}
}

• This action method is chosen when sending a GET request by using the
api/Home/1/Mike path
Using the ApiController Attribute

Use the ApiController attribute to target conventions on the controller:

[Route("api/[controller]")]
[ApiController]
public class CustomerController : ControllerBase
{
[HttpPost]
public void Post(Customer item)
{}
}
Control the HTTP Response

HTTP responses use status codes to express the outcome of the request
processing

public IActionResult Get(string id)


{
if (_items.ContainsKey(id) == false)
return NotFound();

return Ok(_items[id]);
}
Return ActionResult<T>

Returning ActionResult<T> enables you to return a specific type or an object which


inherits from ActionResult

public ActionResult<T> Get(string id)


{
if (_items.ContainsKey(id) == false)
return NotFound();

return _items[id];
}
Data Return Formats

public IEnumerable<string> Get()


{
return new string[] { "value1", "value2" };
}

JSON XML

["value1","value2"]
<ArrayOfstring>
<string>value1</string>
<string>value2</string>
</ArrayOfstring>
Demonstration: How to Develop a Web API

In this demonstration, you will learn how to:

• Add a Web API controller

• Add actions to a Web API controller

• Call Web API from Microsoft Edge

• Control the data return format


Lesson 3: Calling a Web API

01 02 03 04 05
Calling Web APIs Demonstration: Calling Web APIs Working with Demonstration:
by Using jQuery How to call Web by using Server- Complex Objects How to Call Web
Code APIs by Using Side Code APIs by Using
jQuery code Server-Side Code
Calling Web APIs by Using jQuery Code

• You can use jQuery to generate an HTTP request

from a browser to a Web API by using the jQuery


ajax function

• You can use JSON.stringify in the data parameter

of the ajax function to serialize the JavaScript


objects into JSON objects
Calling the Web API Get method by using
jQuery

Calling the Web API Get method by using jQuery:

$(function() {
$.ajax({
url: "http://localhost:[port]/api/values/key1",
type: "GET"
}).done(function (responseText) {
$("#myDiv").text(responseText);
}).fail(function () {
alert("An error has occurred");
});
});
Calling the Web API Post method by using
jQuery

Calling the Web API Post method by using jQuery:

$(function() {
var params = { key: 'key3', value: 'value3' };
$.ajax({
url: "http://localhost:[port]/api/values",
type: "POST",
data: JSON.stringify({ key: 'key3', value: 'value3' }),
contentType: "application/json;charset=utf-8"
}).done(function (responseText) {
$("#myDiv").text("Value added successfully");
}).fail(function () {
alert("An error has occurred");
});
});
Demonstration: How to call Web APIs by Using jQuery
code

In this demonstration, you will learn how to:

• Add a Web API controller with Get and Post


methods

• Call the Web API Get method by using


jQuery

• Call the Web API Post method by using


jQuery
Calling Web APIs by using Server-Side Code

• To call Web APIs by using server-side code:


• Add code to initialize the HttpClient class
• Add code to create requests by using GetAsync, PostAsync, PutAsync and
DeleteAsync

HttpClient client =
_httpClientFactory.CreateClient();
client.BaseAddress = new
Uri("http://localhost:[port]");
HttpResponseMessage response =
client.GetAsync("api/Values/key1").Result;
Working with Complex Objects

Returning complex objects from a Web API

OBJECT

Passing complex objects to a Web API

OBJECT
Get a Complex Object from a Web API

HttpResponseMessage response =
await httpClient.GetAsync("api/Person");
if (response.IsSuccessStatusCode)
{
Person person =
await response.Content.ReadAsAsync<Person>();
return Content(person.Name);
}
else
{
return Content("An error has occurred");
}
Pass a Complex Object to a Web API

Entry entry =
new Entry() { Key = "key3", Value = "value3" };
HttpResponseMessage response =
await httpClient.PostAsJsonAsync("api/Values", entry);
if (response.IsSuccessStatusCode)
{
return Content("succedded");
}
else
{
return Content("An error has occurred");
}
Demonstration: How to Call Web APIs by
Using Server-Side Code

In this demonstration, you will learn how to:


• Register and use the IHttpClientFactory service
• Call a Web API Get method by using the HttpClient class
• Call a Web API Post method by using the HttpClient class
Demonstration: How to Call Web APIs by Using Server-
Side Code

In this demonstration, you will learn how to:


• Register and use the IHttpClientFactory
service
• Call a Web API Get method by using the
HttpClient class
• Call a Web API Post method by using the
HttpClient class
Module 12 Lab:
Implementing Web APIs
Labs and Tasks
Module Review
and Takeaways
Module 13
Hosting and Deployment
Module Overview

On-Premises Hosting Deployment to


01 and Deployment 02 Microsoft Azure

Microsoft Azure
03 Fundamentals
Lesson 1: On-Premises Hosting and Deployment

01 02 03 04
Web Servers Hosting ASP.NET Deploying to IIS File Providers
Core Application
Web Servers

Setting up the server is an important part of an ASP.NET Core MVC application and requires
you to make important decisions

01 02
By choosing Kestrel, you get: By choosing HTTP.sys you get:

• A lightweight server that is fast • A robust framework with many prebuilt

• The ability to use reverse proxy options

• Cross-platform support • Windows-based authentication

• Direct file transfer from the server


Hosting ASP.NET Core Application

For hosting ASP.NET Core MVC applications, you need to decide:

• What configurations are needed as part of the

publishing process

• The server infrastructure to use to host your

application

• Whether to use a reverse proxy as part of your

application

• Whether load balancing functionality is required


Setting Output Path for a Project
Deploying to IIS

• Deploying an application requires a large investment at the start

• It becomes considerably easier on updates

• The first set up requires several steps:

• Update the ASP.NET Core application to work with IIS

• Set up IIS

• Create the IIS Web Site

• Deploy the application

• After the first deployment you can directly perform the deployment
File Providers

File Providers allow us to interact with actual files in the project structure:

PhysicalFileProvider ManifestEmbeddedFileP CompositeFileProvider


rovider

interacts with files that are interacts with files which allows us to combine two
physically present in the are embedded within the or more providers and use
project structure application itself, allowing them all with a single
for added security at the interface
cost of being
unchangeable at run time
Lesson 2: Deployment to Microsoft Azure

01 02 03
What is Microsoft Benefits of Deploying Web
Azure? Hosting in Application on
Microsoft Azure Microsoft Azure

04 05 06
Demonstration: Azure Debugging a
How to Deploy a Deployment Microsoft Azure
Web Application Strategy Application
to Microsoft
Azure
What is Microsoft Azure?

Cloud Service that makes computing resources available on


demand and over the internet

Infrastructure-as-a-Service Platform-as-a-Service

- Compute resources available - Complete environment (OS,


on demand webservers and other
- Resources include: necessary software)
- Virtual machines available on demand
- Persistent disks - Provides auto-scaling,
- Networking maintenance and monitoring
- Containers of systems
- Scale up and down as per - Ease of deployment
demand - Suitable for micro-services
- Pay only for what you use based architecture
Benefits of Hosting in Microsoft Azure

Benefits of Azure:

Efficiency
• With PaaS, deploying and scaling
application is very easy. This leads to
efficient use or resources. Elasticity
• Ability to scale up to thousands of
machines
Security
• Common compliances and certifications
in place. Also provides DDoS
protection, threat protection, and
information protection. Cost
• Pay as you use model means no up-
front investment needed and hence
Developer Tools more cost-effective.
• A wide variety of tools available for
building and deploying your application
automatically.
Deploying Web Application on Microsoft Azure

Azure App Service

• PaaS from Microsoft Azure, provides a managed platform to deploy and host your

applications

• Offers auto-scaling, high availability, and load balancing

• Provides App Insights to monitor application performance

• Applications are hosted on Microsoft’s global infrastructure

• App Service provides easy integration to other Azure services such as Storage, Active

Directory etc.

• Integrates with various tools for continuous deployment


Demonstration: How to Deploy a Web Application to
Microsoft Azure

In this demonstration, you will learn how to:

• Deploy your application to Microsoft Azure App


Service.

• Check the details of the deployed application


in Azure Portal.
Debugging a Microsoft Azure Application

• Application Insights – ability to monitor


applications running in App Service.

• Application Insights provides

• Metrics – such as CPU usage, memory


consumption, page views, performance of
events etc

• Live Stream – ability to see key metrics in a


streaming fashion.

• Analysis from Visual Studio

• Remote Debugging – ability to debug live

applications from Visual Studio

• Server Explorer – Ability to manage Azure Services

from Visual Studio


Module 13 Lab: Hosting and
Deployment
Labs and Tasks
Module Review
and Takeaways
Recap
Q&A
Thank You
elev8me.com

© 2023 elev8 - All rights reserved.

You might also like