SlideShare a Scribd company logo
1 of 118
Download to read offline
Mohamed ELshafei
Prerequisite - Dependency injection (DI)
• Dependency injection (DI) is a technique for achieving loose coupling
between objects and their collaborators, or dependencies. Rather
than directly instantiating collaborators, or using static references, the
objects a class needs in order to perform its actions are provided to
the class in some fashion.
• Most often, classes will declare their dependencies via their
constructor, allowing them to follow the Explicit Dependencies
Principle. This approach is known as "constructor injection"
Prerequisite - Dependency Inversion Principle
(DIP)
• The Dependency Inversion Principle (DIP) states that high level
modules should not depend on low level modules; both should
depend on abstractions (typically interfaces). Abstractions should not
depend on details.
• Details should depend upon abstractions which are provided to them
when the class is constructed.
Prerequisite - containers
• A container is essentially a factory that's responsible for providing
instances of types that are requested from it.
• When a system is designed to use DI, with many classes requesting
their dependencies via their constructor (or properties), it's helpful to
have a class dedicated to creating these classes with their associated
dependencies. These classes are referred to as containers, or more
specifically, Inversion of Control (IoC) containers or Dependency
Injection (DI) containers.
What is ASP.NET Core?
• A new free, open-source, high-performance and cross-platform
framework for building modern cloud-based Web applications using
.NET
• ASP.NET Core is a modular framework distributed as NuGet packages.
This allows us to include packages that are required in our
application.
ASP.NET Core
• ASP.NET Core is designed to be deployed on cloud as well as on-
premises. Developers can now build cloud-based web applications, IoT
(Internet of Thing) and mobile backend applications using ASP.NET
Core framework which can run on Windows, Linux, and Mac operating
systems.
• ASP.NET Core Version History
Version Release Date
ASP.NET Core 2.0 August 2017
ASP.NET Core 1.1 November 2016
ASP.NET Core 1.0 June 2016
.NET Core != ASP.NET Core
• ASP.NET Core and .NET Core are not the same. They are different, just
like ASP.NET and .NET Framework are different.
• .NET Core is a fast, lightweight, modular and open source framework
for creating web applications and services that run on Windows, Linux
and Mac. So, it is a platform on which ASP.NET Core application runs.
• .NET Core is named "Core" because it includes core features of the
.NET framework.
.NET Core components
• ASP.NET Core is a part of .NET Core SDK so you don't need to install ASP.NET Core
separately.
• .NET Core comes under Apache 2 licenses. Visit .NET Core repository on Github to
contribute or download the source code.
Why ASP.NET Core?
• Supports Multiple Platforms: ASP.NET Core applications can run on
Windows, Linux, and Mac. So you don't need to build different apps
for different platforms using different frameworks.
• Fast - 8x Faster than Node; 3x Faster than Go .. ASP.NET Core no
longer depends on System.Web.dll for browser-server
communication. ASP.NET Core allows us to include packages which
we need for our application. This reduces the request pipeline and
improves the performance and scalability.
• IoC Container: It includes built-in IoC container for automatic
dependency injection which makes it maintainable and testable.
• Open-Source with Contributions – even the docs
Why ASP.NET Core?
• Integration with Modern UI Frameworks: It allows you to use and
manage modern UI frameworks such as AngularJS, ReactJS, Umber,
Bootstrap etc. using Bower (a package manager for the web).
• Smaller Deployment Footprint: ASP.NET Core application runs on
.NET Core which is smaller than full .NET Framework. So, the
application which uses only a part of .NET CoreFX will have smaller
deployment size. This reduces the deployment foot print.
• Hosting: ASP.NET Core web application can be hosted on multiple
platforms with any web server such as IIS, Apache etc. It is not
dependent only on IIS as a standard .NET Framework.
• Choice of Tools and Editors – Any Text Editor plus CLI, or Visual Studio
.NET Core 2.0 -Supported OS versions
ASP.NET Core ASP.NET
Build for Windows, macOS, or Linux Build for Windows
Razor Pages is the recommended approach to
create a Web UI as of ASP.NET Core 2.x. See
also MVC, Web API, and SignalR.
Use Web Forms, SignalR, MVC, Web API, or Web
Pages
Develop with Visual Studio, Visual Studio for Mac,
or Visual Studio Code using C# or F#
Develop with Visual Studio using C#, VB, or F#
Higher performance than ASP.NET Good performance
Choose .NET Framework or .NET Core runtime Use .NET Framework runtime
Compilation Process
.NET Core Runtime
• .NET Core SDK can be installed on the platform you are using such as
Windows, Linux or Mac.
• .NET Core Runtime and .NET Core SDK are different things.
• .NET Core Runtime is only used to run .NET Core application whereas
.NET Core SDK includes tools and libraries to develop .NET Core
applications.
Getting the Bits
• Install SDK
https://www.microsoft.com/net/download/core
• Optional: Install Visual Studio 2017
Install VS2017 .NET Core 2.0 Tools
• Confirm Version:
Windows
Linux
MacOS
Command-line Interface (CLI)
• If you do not use Visual Studio for .NET core application development for
some reason and want to use different IDE then you can use command-line
interface to create, compile, build, restore and run .NET Core application.
• .NET Core SDK installation also installs command-line interface for the
selected platform. It installs the latest stable version of the tools and put
them on your PATH so you can run dotnet from the Console.
• .NET Core command-line interface (CLI) tools
https://docs.microsoft.com/en-us/dotnet/core/tools/?tabs=netcore2x
• Getting started with .NET Core using the command line
https://docs.microsoft.com/en-us/dotnet/core/tutorials/using-with-xplat-cli
New Installer!
File > New Project > Web
• ASP .NET Core Web App
• Web App (4.x)
Select a Template
1.0 , 1.1, 2.0 Templates
• Empty
• Web API
• Web App (Razor)
• Web App (MVC)
• Angular
• React.js
• React.js & Redux
Other settings:
• Authentication
• Docker Support
ASP.NET Core Project Structure (Empty Project )
We can change it to folder view by clicking Solution
and Folders icon.
ASP.NET Core project files and folders are
synchronized with physical files and folders.
Dependencies
• The Dependencies in the ASP.NET Core 2.0 project contain all the
installed server-side NuGet packages as well as client-side
frameworks such as jQuery, AngularJS, Bootstrap etc. These client-
side dependencies are managed using Bower in Visual Studio.
Bower “A package manager for the web”
• Bower calls itself "A package manager for the web". Within the .NET
ecosystem, it fills the void left by NuGet's inability to deliver static content
files
• New projects created with the ASP.NET Core project templates set up the
client-side build process. jQuery and Bootstrap are installed, and Bower is
supported.
• Client-side packages are listed in the bower.json file. The ASP.NET Core
project templates configures bower.json with jQuery, jQuery validation, and
Bootstrap.
Properties
• The Properties node includes launchSettings.json file which includes
Visual Studio profiles of debug settings. The following is a default
launchSettings.json file.
Edit debug settings from the
debug tab of project
properties.
Right click on the project -> select
Properties -> click Debug tab.
Right-click > (Project) Properties
wwwroot
• wwwroot folder is treated as a web root folder. Static files can be
stored in any folder under the web root and accessed with a relative
path to that root.
• only files that are in wwwroot folder can be served over an http
request. All other files are blocked and
cannot be served by default.
wwwroot
• Generally, there should be separate folders for the different types of
static files such as JavaScript, CSS, Images, library scripts etc
• You can access static files with base URL and file name.
For example, we can access site.css file in the css folder
by http://localhost:<port>/css/app.css.
• you need to include a middleware for serving static files in the
Configure method of Startup.cs.
Program.cs
• ASP.NET Core web application is actually a console project which
starts executing from the entry point public static void Main() in
Program class where we can create a host for the web application.
• The steps for creating a host in ASP.NET Core 1.x is different in
ASP.NET Core 2.x.
WebHostBuilder (1.x)
• The WebHostBuilder class is the helper class to create and configure a
host for a web application.
• The UseKestrel() method is an extension method which specifies Kestrel
as an internal web server.
• The Kestrel is an open-source, cross-platform web server for ASP.NET
Core. It is designed to be used behind proxy because it has not yet
matured to be exposed as a full-fledge web server.
• ASP.NET Core application can be a cross-platform application so it can be
used with any web server, and not only IIS.
• There will be an external web server such as IIS, Apache, Nginx etc. which
will dispatch http requests to the internal web server Kestrel.
• The UseContentRoot() method specifies the current directory as a root
directory which will be src folder in the default ASP.NET Core project.
• The UseIISIntegration() method specifies the IIS as the external web server or
the reverse proxy server.
• The UseStartup<startup>() method specifies the Startup class to be used by
the web host. Startup class is like Global.asax of .NET framework where you
can configure request pipeline (middleware).
• The Build() method returns an instance of IWebHost using the configuration
specified above.
• The Run() method starts the web application and blocks the calling thread till
the host is shutdown
The command line application will become web application from this point onwards.
WebHostBuilder (2.x)
Startup Class
• ASP.NET Core application must include Startup class. It is like
Global.asax in the traditional .NET application.
• Startup class includes two public methods
ConfigureServices and Configure.
Startup ConfigureServices
• The Dependency Injection pattern is used heavily in ASP.NET Core
architecture.
• ConfigureServices includes built-in IoC container to provide dependent
objects using constructors.
• you can register your dependent classes with the built-in IoC container
using IServiceCollection.
• After registering dependent class, it can be used anywhere in the
application. You just need to include it in the parameter of the
constructor of a class where you want to use it. The IoC container will
inject it automatically.
• You can Configure third-party container like StructureMap, Unity, Autofac, Ninject,
Castle Windsor, etc.
Dependency Injection in ASP.NET Core
• ASP.NET Core is designed from scratch to support Dependency
Injection.
• ASP.NET Core injects objects of dependency classes through
constructor or method by using built-in IoC container.
• The built-in container is represented by IServiceProvider
implementation that supports constructor injection by default. The
types (classes) managed by built-in IoC container is called services.
• Framework Services: Services which are a part of ASP.NET Core framework
such as IApplicationBuilder, IHostingEnvironment, ILoggerFactory etc.
• Application Services: The services (custom types or classes) which you as a
programmer create for your application.
Startup ConfigureServices (2.0)
Service lifetimes and registration options
• Transient
Transient lifetime services are created each time they're
requested. This lifetime works best for lightweight, stateless services.
• Scoped
Scoped lifetime services are created once per request.
• Singleton
Singleton lifetime services are created the first time they're
requested (or when ConfigureServices is run if you specify an instance
there) and then every subsequent request will use the same instance.
Startup.Configure
• The Configure method is a place where you can configure application
request pipeline for your application using IApplicationBuilder instance that
is provided by the built-in IoC container.
• ASP.NET Core introduced the middleware components to define a request
pipeline, which will be executed on every request.
• You include only those middleware components which are required by your
application and thus increase the performance of your application.
• At run time, the ConfigureServices method is called before the Configure
method. This is so that you can register your custom service with the IoC
container which you may use in the Configure method.
Middleware “Built-in and Custom”
A middleware is nothing but a component (class) which is executed on
every request in ASP.NET Core application.
It can be either framework provided middleware, added via NuGet or
your own custom middleware.
• Each component in the pipeline is a request delegate.
• Each delegate can invoke the next component in the chain, or short-
circuit, returning back up the call chain
ASP.NET Core Request Processing
built-in middleware
Middleware Description
Authentication Adds authentication support.
CORS Configures Cross-Origin Resource Sharing.
Routing Adds routing capabilities for MVC
Session Adds support for user session.
StaticFiles Adds support for serving static files and directory browsing.
Diagnostics Adds support for reporting and handling exceptions and errors.
MVC Adds support for using MVC pattern
Diagnostics Middleware
Middleware Extension Method Description
DeveloperExceptionPageMiddleware UseDeveloperExceptionPage() Captures synchronous and
asynchronous exceptions from the
pipeline and generates HTML error
responses.
ExceptionHandlerMiddleware UseExceptionHandler() Catch exceptions, log them and re-
execute in an alternate pipeline.
StatusCodePagesMiddleware UseStatusCodePages() Check for responses with status codes
between 400 and 599.
WelcomePageMiddleware UseWelcomePage() Display Welcome page for the root path.
Creating Middleware in Startup: Run
Creating Middleware in Startup: Use
Creating Middleware in Startup: Map
Startup Configure (2.0)
UseStaticFiles Middleware
• For the wwwroot folder
app.UseStaticFiles();
• For your own folder
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), “your own folder path")),
RequestPath = "/StaticFiles“ // URLrequest path
});
Project Dependencies (1.x)
New Project Dependencies (2.0)
appsettings.json - project.json
• The project.json file includes settings for an application which is used
by .NET Core CLR (runtime) to determine how to run an application.
Choose Profile While Debugging
Install Entity Framework Core
https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/new-db
Working With a Database Using EF Core
• Add Entity Framework Core (EF Core) in ConfigureServices:
• Also supports InMemory – Install this package:
and modify ConfigureServices:
Working with EF Core’s AppDbContext
• Never directly instantiate your application’s DbContext type(s)
• Instead, request from DI using constructor parameters
Recommendation
• Follow the Dependency Inversion Principle and avoid having UI types
depend on details
• Using Entity Framework Core is an implementation detail
• Instead depend on an abstraction over your persistence method
• Common pattern for this: Repository
Razor Pages
Mohamed ELshafei
Razor Pages
• Razor Pages is an exciting new product released with ASP.NET Core 2,
which makes building webpages without an MVC framework quick
and easy.
• Razor Pages is a new feature of ASP.NET Core that makes coding
page-focused scenarios easier and more productive.
• The most importantly thing to know about Razor Pages is that they
are built on top of ASP.NET Core MVC, not beside it, and so all the
goodness from ASP.NET MVC applications (routing, ModelState, etc.)
you can still access in Razor Pages apps.
Razor Pages
• All of the Razor Pages types and features live in the
Microsoft.AspNetCore.Mvc.RazorPages assembly.
• The MVC package – Microsoft.AspNetCore.Mvc includes the Razor
Pages assembly.
• That means that you can use Razor Pages out of the box with MVC.
HOW?
• If you want to build few simple pages with MVC, you have controller
actions in separate place, HTML for view in separate place, ViewModel in a
different location, routes in separate place, and that just seems like too
much.
• With Razor Pages, you have this one Razor file (.cshtml), and the code for a
single page lives inside of that file, and that file also represents the URL
structure of the app . Therefore, you got everything inside of one file, and it
just works.
• However, you CAN separate your code to the code behind file
with .cshtml.cs extension. You would usually have your view model and
handlers (like action methods in MVC) in that file and handle the logic
there.
Creating Razor Pages app
• With VS 2017 and .NET Core 2 SDK installed if we follow the old
standard path in Visual Studio: File -> New Project -> Web -> ASP.NET
Core Web Application we will get the following screen:
Project files and folders
File or folder Purpose
wwwroot Contains static files. See Work with static files.
Pages Folder for Razor Pages.
appsettings.json Configuration
Program.cs Hosts the ASP.NET Core app.
Startup.cs Configures services and the request pipeline.
See Startup.
The Pages folder
• The _Layout.cshtml file contains common HTML elements (scripts and stylesheets) and
sets the layout for the application.
• The _ViewStart.cshtml sets the Razor Pages Layout property to use the _Layout.cshtml
file.
• The _ViewImports.cshtml file contains Razor directives that are imported into each Razor
Page.
• The _ValidationScriptsPartial.cshtml file provides a reference to jQuery validation scripts.
• The About, Contact and Index pages are basic pages you can use to start an app. The
Error page is used to display error information.
Configure bundling and minification
• The MVC and Razor Pages project templates provide
a bundleconfig.json configuration file which defines the options for
each bundle.
• By default, a single bundle configuration is defined for the custom
JavaScript (wwwroot/js/site.js) and stylesheet (wwwroot/css/site.css)
files
• https://docs.microsoft.com/en-us/aspnet/core/client-side/bundling-
and-minification
Razor Pages is enabled in Startup.cs:
@page Directive
• @page makes the file into an MVC action - which means that it
handles requests directly, without going through a controller.
• @page must be the first Razor directive on a page.
• the PageModel class file has the same name as the Razor Page file
with .cs appended
Determine URL paths to pages
• The associations of URL paths to pages are determined by the page's
location in the file system.
• The runtime looks for Razor Pages files in the Pages folder by default.
• Index is the default page when a URL doesn't include a page.
File name and path matching URL
/Pages/Index.cshtml / or /Index
/Pages/Contact.cshtml /Contact
/Pages/Store/Contact.cshtml /Store/Contact
/Pages/Store/Index.cshtml /Store or /Store/Index
URL generation for Pages -Example
• URL generation for pages supports relative names.
• The following table shows which Index page is selected with different
RedirectToPage parameters from Pages/Customers/Create.cshtml
RedirectToPage(x) Page
RedirectToPage("/Index") Pages/Index
RedirectToPage("./Index"); Pages/Customers/Index
RedirectToPage("../Index") Pages/Index
RedirectToPage("Index") Pages/Customers/Index
RedirectToPage("Index"),
RedirectToPage("./Index"), and
RedirectToPage("../Index") are relative
names.
The RedirectToPage parameter is
combined with the path of the current
page to compute the name of the
destination page.
PageModel
• the PageModel class is called <PageName>Model and is in the same
namespace as the page.
• The PageModel class allows separation of the logic of a page from its
presentation.
• It defines page handlers for requests sent to the page and the data
used to render the page.
• You can add handler methods for any HTTP verb. The most common
handlers are:
• OnGet to initialize state needed for the page.
• OnPost to handle form submissions.
[BindProperty]
• Razor Pages, by default, bind properties only with non-GET verbs.
Binding to properties can reduce the amount of code you have to
write. Binding reduces code by using the same property to render
form fields.
• To bind a property on GET requests, set the [BindProperty] attribute's
Supports Get property to true: [BindProperty(SupportsGet = true)]
Customizing Routing - @page "{id:int}"
• The routing constraint"{id:int}" tells the page to accept requests to
the page that contain int route data.
• If a request to the page doesn't contain route data that can be
converted to an int, the runtime returns an HTTP 404 (not found)
error.
• To make the ID optional, append ? to the route constraint: @page
"{id:int?}"
Multiple handlers per page
• The asp-page-handler attribute is a companion to asp-page. asp-
page-handler generates URLs that submit to each of the handler
methods defined by a page.
The preceding code uses named handler methods.
Named handler methods are created by taking the text in
the name after On<HTTP Verb> and before Async
(if present)
Configuration and settings
• you can use the RazorPagesOptions to set the root directory for
pages, or add application model conventions for pages.
Custom root directory
• Add WithRazorPagesRoot to AddMvc to specify that your Razor Pages
are at a custom root directory in the app (provide a relative path):
Browser Link in ASP.NET Core
• Browser Link is a feature in Visual Studio that creates a
communication channel between the development environment and
one or more web browsers. You can use Browser Link to refresh your
web application in several browsers at once, which is useful for cross-
browser testing.
• Configuration
In the Configure method of the Startup.cs file:
app.UseBrowserLink();
How to use Browser Link
From the Browser Link toolbar control, you can:
• Refresh the web application in several browsers at once.
• Open the Browser Link Dashboard.
• Enable or disable Browser Link. Note: Browser Link is disabled by default in
Visual Studio 2017 (15.3).
• Enable or disable CSS Auto-Sync.
Open multiple browsers at once
To open multiple browsers at once, choose Browse with... from the same
drop-down. Hold down the CTRL key to select the browsers you want, and
then click Browse
Enable or disable CSS Auto-Sync
• When CSS Auto-Sync is enabled, connected browsers are
automatically refreshed when you make any change to CSS files.
How does it work?
Browser Link uses SignalR to create a communication channel between
Visual Studio and the browser.
When Browser Link is enabled, Visual Studio acts as a SignalR server
that multiple clients (browsers) can connect to.
Browser Link also registers a middleware component in the ASP.NET
request pipeline. This component injects special <script> references
into every page request from the server.
Tag Helpers
• Tag Helpers enable server-side code to participate in creating and rendering
HTML elements in Razor files.
• Replaces HTML Helpers (still available, but not recommended)
• Render within HTML tags
• A rich IntelliSense environment for creating HTML and Razor markup
• There are many built-in Tag Helpers for common tasks - such as creating forms,
links, loading assets and more
• @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
• https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-
in/index?view=aspnetcore-2.0
Managing Tag Helper scope
• Tag Helpers scope is controlled by a combination of @addTagHelper,
@removeTagHelper, and the "!" opt-out character.
• @addTagHelper makes Tag Helpers available.
• @removeTagHelper removes Tag Helpers.
• You can disable a Tag Helper at the element level with the Tag Helper
opt-out character ("!")
<!span asp-validation-for="Email" class="text-danger"></!span>
IntelliSense support for Tag Helpers
• When you create a new ASP.NET web app in Visual Studio, it adds the
NuGet package "Microsoft.AspNetCore.Razor.Tools". This is the
package that adds Tag Helper tooling
Tag Helper Example
Author Tag Helpers
• A tag helper is any class that implements the ITagHelper interface.
However, when you author a tag helper, you generally derive from
TagHelper, doing so gives you access to the Process method.
• Add the yourTagHelper class to the TagHelpers folder.
• To make the yourTagHelper class available to all our Razor views, add
the addTagHelper directive to the Views/_ViewImports.cshtml .
Razor Pages
• Razor Pages are Page focused way of programming web sites
• You can(if you want to) have all the code and HTML in one place
• The location of Razor page file determines the URL/route for your page
• Razor Pages are not a reincarnation of old ASP.NET Web Pages
• Features that we can use with MVC we can also use with Razor Pages:
• Model Binding
• Razor support
• Tag Helpers
• HTML Helpers
• Handlers (Action Methods)
• etc..
• We have handlers (OnGet, OnGetAsync, OnPostAsync etc..)
• Location of the page in file system (project structure) determines the URL path
• Need to have one root folder
• Stored in Pages root folder by default (configurable)
MVC
Mohamed ELshafei
ASP.NET Core MVC with EF Core
• EF Core 2.0 is the latest version of EF but doesn't yet have all the
features of EF 6.x.
• To add EF Core support to a project, install the database provider that
you want to target. This tutorial uses SQL Server, and the provider
package is Microsoft.EntityFrameworkCore.SqlServer. This package is
included in the Microsoft.AspNetCore.All metapackage, so you don't
have to install it.
• This package and its dependencies (Microsoft.EntityFrameworkCore
and Microsoft.EntityFrameworkCore.Relational) provide runtime
support for EF.
Install Entity Framework Core
https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/new-db
Working With a Database Using EF Core
• Add Entity Framework Core (EF Core) in ConfigureServices:
• Also supports InMemory – Install this package:
and modify ConfigureServices:
Using EF Core’s AppDbContext
• 1- install Entity Framework Core NuGet packages.
• 2- Create the data model
• 3- Create the Database Context
• 4-Add your connection string in appsettting.json
• 5- Register the context with dependency injection
• 6-Add Migration and Update Database.
Working with EF Core’s AppDbContext
• Never directly instantiate your application’s DbContext type(s)
• Instead, request from DI using constructor parameters
Recommendation
• Follow the Dependency Inversion Principle and avoid having UI types
depend on details
• Using Entity Framework Core is an implementation detail
• Instead depend on an abstraction over your persistence method
• Common pattern for this: Repository
Loading Related Data
Entity Framework Core allows you to use the navigation properties in your
model to load related entities. There are three common O/RM patterns used
to load related data.
• Eager loading means that the related data is loaded from the database as
part of the initial query.
• Explicit loading When the entity is first read, related data isn't retrieved.
You write code that retrieves the related data if it's needed.
• Lazy loading When the entity is first read, related data isn't retrieved.
However, the first time you attempt to access a navigation property, the
data required for that navigation property is automatically retrieved.
Eager loading
• You can use the Include method to specify related data to be included
in query results.
• You can include related data from multiple relationships in a single
query.
Including multiple levels -Eager loading
• You can drill down thru relationships to include multiple levels of
related data using the ThenInclude method.
• Note: Visual Studio offer incorrect code completion options when
using the ThenInclude This is a symptom of an IntelliSense bug . It is
safe to ignore these spurious syntax errors as long as the code is
correct and can be compiled successfully.
Explicit loading
• This feature was introduced in EF Core 1.1.
• When the entity is first read, related data isn't retrieved. You write
code that retrieves the related data if it's needed.
• you can use the Load method to do explicit loading.
Lazy loading
• This feature was introduced in EF Core 2.1.
• The simplest way to use lazy-loading is by installing the
Microsoft.EntityFrameworkCore.Proxies package and enabling it with
a call to UseLazyLoadingProxies when using AddDbContext:
EF Core will then enable lazy-loading for any navigation property that
can be overridden--that is, it must be virtual and on a class that can be
inherited from.
Performance considerations
• If you know you need related data for every entity retrieved, eager
loading often offers the best performance, because a single query
sent to the database is typically more efficient than separate queries
for each entity retrieved.
• In some scenarios separate queries is more efficient. Eager loading of
all related data in one query might cause a very complex join to be
generated, which SQL Server can't process efficiently.
Repository Pattern In ASP.NET Core MVC And
Entity Framework Core
The repository pattern is intended to create an Abstraction layer
between the Data Access layer and Business Logic layer of an
Application. It is a data access pattern that prompts a more loosely
coupled approach to data access. We create a generic repository, which
queries the data source for the data, maps the data from the data
source to a business entity and persists changes in the business entity
to the data source
WHY?
• We implement repository pattern to develop a loosely coupled application.
It makes the code more testable. It creates an abstraction layer between
ORM and business logic layer of the application.
• the repository mediates between the data source layer (Entity Framework)
and the business layer (Controller) of the application. It performs
operations as following way.
• It queries the underlying data source (database) for the data.
• It maps the data from the data source to a business entity that uses to create the
database.
• It persists changes in the business entity to the data source.
Advantages of Repository Pattern
It has some advantages which are as follows:
• An entity might have many operations which perform from many locations
in the application, so we write logic for common operations in the
repository. These operations might be Create, Read, Update, Delete,
Search, Filter, Sort, Paging, and Caching etc.
• The Entity Framework is not testable out of the box. We have to create
mock classes to test it. Data access logic can be tested using repository
pattern.
• As business logic and data access logic separate in the repository pattern
that’s why it easy to manage and readable. It reduces development as well
me, as common functionality logic writes once in the application.
How? “Employee Entity”
• ASP.NET Core is designed to support dependency injection. So, we
create a repository interface named IEmployeeRepository for
Employee .
• This interface has definitions of all methods to perform CRUD
operations on the Employee entity.
• let’s implement the preceding interface on a class named
EmployeeRepository.
• This class has implemention of all methods to perform CRUD
operations on the Employee entity. It has a parameterized constructor
that accepts Context as a parameter. It passes at a time of repository
instance creates by dependency injection.
How? “Employee Entity” cont..
• web application communicates to data access layer via an interface so
we register repository to the dependency injection during the
application start up.
• Create Application User Interface
• create a view model named EmployeeViewModel for application UI
and CRUD operations. This model strongly binds with a view.
Routing to controller actions in ASP.NET Core
• Actions are either conventionally routed or attribute routed. Placing a
route on the controller or the action makes it attribute routed.
• With attribute routing the controller name and action names
play no role in which action is selected.
Attribute routing with Http[Verb] attributes.
• Attribute routing can also make use of the Http[Verb] attributes such
as HttpPostAttribute. All of these attributes can accept a route
template.
Token replacement in route templates
• For convenience, attribute routes support token replacement by
enclosing a token in square-braces ([, ]).
• No route Prefix.
Multiple Routes
Specifying attribute route optional
parameters, default values, and constraints
• {id:int} integar constraint.
• {id:int?} optional Parameter
• {id:int=3} Default Value
IActionResult
there are a wide range of ways that you can return content from MVC
controllers that aren't limited to just ActionResults.
• ContentResult
• EmptyResult
• FileResult
• HttpStatusCodeResult
• JavaScriptResult
• JsonResult
• RedirectResult
• RedirectToRouteResult
View components in ASP.NET Core
• New to ASP.NET Core MVC, view components are similar to partial
views, but they're much more powerful. View components don't use
model binding, and only depend on the data provided when calling
into it.
A view component:
• Renders a chunk rather than a whole response.
• Includes the same separation-of-concerns and testability benefits found
between a controller and view.
• Can have parameters and business logic.
• Is typically invoked from a layout page.
Using of View components
View components are intended anywhere you have reusable rendering logic
that's too complex for a partial view.
• Dynamic navigation menus
• Tag cloud (where it queries the database)
• Login panel
• Shopping cart
• Recently published articles
• Sidebar content on a typical blog
• A login panel that would be rendered on every page and show either the
links to log out or log in, depending on the log in state of the user
Creating a view component
• A view component class can be created by Deriving from ViewComponent class.
• A view component defines its logic in an InvokeAsync method that returns an
IViewComponentResult.
• Parameters come from the calling method, not HTTP, there's no model binding
• The runtime searches for the view in the following paths:
• Views/<controller_name>/Components/<view_component_name>/<view_name>
• Views/Shared/Components/<view_component_name>/<view_name>
• The default view name for a view component is Default, which means your view file
will typically be named Default.cshtml.
• We recommend you name the view file Default.cshtml and use
the Views/Shared/Components/<view_component_name>/<view_name> path.
Invoking a view component
• To use the view component, call the following inside a view:
• Invoking a view component as a Tag Helper
In order to use a View Component as a Tag Helper, you must register the assembly containing the
View Component using the @addTagHelper directive
if your View Component is in an assembly called "MyWebApp", add the following directive to the
_ViewImports.cshtml file:@addTagHelper *, MyWebApp
Tag Helpers
• Tag Helpers enable server-side code to participate in creating and rendering
HTML elements in Razor files.
• Replaces HTML Helpers (still available, but not recommended)
• Render within HTML tags
• A rich IntelliSense environment for creating HTML and Razor markup
• There are many built-in Tag Helpers for common tasks - such as creating forms,
links, loading assets and more
• @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
• https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-
in/index?view=aspnetcore-2.0
Managing Tag Helper scope
• Tag Helpers scope is controlled by a combination of @addTagHelper,
@removeTagHelper, and the "!" opt-out character.
• @addTagHelper makes Tag Helpers available.
• @removeTagHelper removes Tag Helpers.
• You can disable a Tag Helper at the element level with the Tag Helper
opt-out character ("!")
<!span asp-validation-for="Email" class="text-danger"></!span>
IntelliSense support for Tag Helpers
• When you create a new ASP.NET web app in Visual Studio, it adds the
NuGet package "Microsoft.AspNetCore.Razor.Tools". This is the
package that adds Tag Helper tooling
Tag Helper Example
Author Tag Helpers
• A tag helper is any class that implements the ITagHelper interface.
However, when you author a tag helper, you generally derive from
TagHelper, doing so gives you access to the Process method.
• Add the yourTagHelper class to the TagHelpers folder.
• To make the yourTagHelper class available to all our Razor views, add
the addTagHelper directive to the Views/_ViewImports.cshtml .
References
• ASP .NET: http://www.asp.net
• .NET Core: https://www.microsoft.com/net
• .NET Web Dev Blog: https://blogs.msdn.microsoft.com/webdev
• Scott Hanselman’s Blog: https://www.hanselman.com/blog
• .NET Conf: http://www.dotnetconf.net
• MSDN Channel 9: https://channel9.msdn.com
• Tutorials: https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-
mvc-app
• C# 7: https://docs.microsoft.com/en-us/dotnet/articles/csharp/csharp-7
• ASP.NET Core Roadmap: https://github.com/aspnet/Home/wiki/Roadmap
References
• New Razor Pages: http://www.hishambinateya.com/welcome-razor-pages
• Intro to Razor: https://docs.microsoft.com/en-us/aspnet/core/mvc/razor-
pages
• Migrating from MVC to MVC Core:
https://docs.microsoft.com/enus/aspnet/core/migration/mvc
• .NET core : https://mva.microsoft.com/learning-path/aspnet-core-20-
23?MC=ASPNET
• Repository Pattern in ASP.Net Core mvc :
http://l-knowtech.com/2017/09/12/repository-pattern-asp-net-core-mvc-
entity-framework-core/
References
Try ASP.NET Core course:
https://www.codeschool.com/courses/try-asp-net-core
ASP.NET CoreQuick Start :
http://aspnetcorequickstart.com/
Razor Pages :
http://www.dotnet-stuff.com/tutorials/aspnet-core/introduction-to-razor-pages-in-
asp-net-core
Introduction to ASP.NET Core Razor Pages - Damian Edwards:
https://www.youtube.com/watch?v=yyBijyCI5Sk
Simpler ASP.NET Apps with Razor Pages :
https://msdn.microsoft.com/en-us/magazine/mt842512.aspx

More Related Content

What's hot

ASP.NET MVC.
ASP.NET MVC.ASP.NET MVC.
ASP.NET MVC.Ni
 
Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Steven Smith
 
Nakov - .NET Framework Overview - English
Nakov - .NET Framework Overview - EnglishNakov - .NET Framework Overview - English
Nakov - .NET Framework Overview - EnglishSvetlin Nakov
 
Introduction to .NET Core
Introduction to .NET CoreIntroduction to .NET Core
Introduction to .NET CoreMarco Parenzan
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentationivpol
 
JEE Course - JEE Overview
JEE Course - JEE  OverviewJEE Course - JEE  Overview
JEE Course - JEE Overviewodedns
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action Alex Movila
 
Modern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and ThymeleafModern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and ThymeleafLAY Leangsros
 
Bootstrap 3
Bootstrap 3Bootstrap 3
Bootstrap 3Lanh Le
 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQLAdil Mehmoood
 
Introduction to react native
Introduction to react nativeIntroduction to react native
Introduction to react nativeDani Akash
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlArjun Thakur
 
.NET Core, ASP.NET Core Course, Session 6
.NET Core, ASP.NET Core Course, Session 6.NET Core, ASP.NET Core Course, Session 6
.NET Core, ASP.NET Core Course, Session 6aminmesbahi
 

What's hot (20)

ASP.NET MVC.
ASP.NET MVC.ASP.NET MVC.
ASP.NET MVC.
 
Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0Introducing ASP.NET Core 2.0
Introducing ASP.NET Core 2.0
 
Nakov - .NET Framework Overview - English
Nakov - .NET Framework Overview - EnglishNakov - .NET Framework Overview - English
Nakov - .NET Framework Overview - English
 
Introduction to .NET Core
Introduction to .NET CoreIntroduction to .NET Core
Introduction to .NET Core
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Asp.net.
Asp.net.Asp.net.
Asp.net.
 
JEE Course - JEE Overview
JEE Course - JEE  OverviewJEE Course - JEE  Overview
JEE Course - JEE Overview
 
Dot Net Core
Dot Net CoreDot Net Core
Dot Net Core
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
Modern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and ThymeleafModern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and Thymeleaf
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Bootstrap 3
Bootstrap 3Bootstrap 3
Bootstrap 3
 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQL
 
Spring framework 3
Spring framework 3Spring framework 3
Spring framework 3
 
Xke spring boot
Xke spring bootXke spring boot
Xke spring boot
 
Introduction to react native
Introduction to react nativeIntroduction to react native
Introduction to react native
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 
.NET Core, ASP.NET Core Course, Session 6
.NET Core, ASP.NET Core Course, Session 6.NET Core, ASP.NET Core Course, Session 6
.NET Core, ASP.NET Core Course, Session 6
 

Similar to Asp.Net Core MVC , Razor page , Entity Framework Core

ASP.NET Core: The best of the new bits
ASP.NET Core: The best of the new bitsASP.NET Core: The best of the new bits
ASP.NET Core: The best of the new bitsKen Cenerelli
 
.NET Core: a new .NET Platform
.NET Core: a new .NET Platform.NET Core: a new .NET Platform
.NET Core: a new .NET PlatformAlex Thissen
 
Introduction to Containers & Diving a little deeper into the benefits of Con...
 Introduction to Containers & Diving a little deeper into the benefits of Con... Introduction to Containers & Diving a little deeper into the benefits of Con...
Introduction to Containers & Diving a little deeper into the benefits of Con...Synergetics Learning and Cloud Consulting
 
White Paper : ASP.NET Core AngularJs 2 and Prime
White Paper : ASP.NET Core AngularJs 2 and PrimeWhite Paper : ASP.NET Core AngularJs 2 and Prime
White Paper : ASP.NET Core AngularJs 2 and PrimeHamida Rebai Trabelsi
 
.NET Core, ASP.NET Core Course, Session 1
.NET Core, ASP.NET Core Course, Session 1.NET Core, ASP.NET Core Course, Session 1
.NET Core, ASP.NET Core Course, Session 1aminmesbahi
 
Asp.NETZERO - A Workshop Presentation by Citytech Software
Asp.NETZERO - A Workshop Presentation by Citytech SoftwareAsp.NETZERO - A Workshop Presentation by Citytech Software
Asp.NETZERO - A Workshop Presentation by Citytech SoftwareRitwik Das
 
Introduction to dot net
Introduction to dot netIntroduction to dot net
Introduction to dot netQIANG XU
 
AWS Summit Auckland - Moving MS .NET Applications One Container at a Time
AWS Summit Auckland - Moving MS .NET Applications One Container at a TimeAWS Summit Auckland - Moving MS .NET Applications One Container at a Time
AWS Summit Auckland - Moving MS .NET Applications One Container at a TimeAmazon Web Services
 
Moving microsoft .net applications one container at a time
 Moving microsoft .net applications one container at a time  Moving microsoft .net applications one container at a time
Moving microsoft .net applications one container at a time Amazon Web Services
 
.NET Core, ASP.NET Core Course, Session 18
 .NET Core, ASP.NET Core Course, Session 18 .NET Core, ASP.NET Core Course, Session 18
.NET Core, ASP.NET Core Course, Session 18aminmesbahi
 
Developing Applications on AWS with .NET Core - DEV330 - re:Invent 2017
Developing Applications on AWS with .NET Core - DEV330 - re:Invent 2017Developing Applications on AWS with .NET Core - DEV330 - re:Invent 2017
Developing Applications on AWS with .NET Core - DEV330 - re:Invent 2017Amazon Web Services
 
SOLID Programming with Portable Class Libraries
SOLID Programming with Portable Class LibrariesSOLID Programming with Portable Class Libraries
SOLID Programming with Portable Class LibrariesVagif Abilov
 
Full session asp net mvc vs aspnet core
Full session asp net mvc vs aspnet coreFull session asp net mvc vs aspnet core
Full session asp net mvc vs aspnet corefizmhd
 
Introduction to ASP.NET 5
Introduction to ASP.NET 5Introduction to ASP.NET 5
Introduction to ASP.NET 5mbaric
 
Pottnet Meetup Essen - ASP.Net Core
Pottnet Meetup Essen - ASP.Net CorePottnet Meetup Essen - ASP.Net Core
Pottnet Meetup Essen - ASP.Net CoreMalte Lantin
 
Pottnet MeetUp Essen - ASP.Net Core
Pottnet MeetUp Essen - ASP.Net CorePottnet MeetUp Essen - ASP.Net Core
Pottnet MeetUp Essen - ASP.Net CoreMalte Lantin
 
Unboxing ASP.NET Core
Unboxing ASP.NET CoreUnboxing ASP.NET Core
Unboxing ASP.NET CoreKevin Leung
 

Similar to Asp.Net Core MVC , Razor page , Entity Framework Core (20)

ASP.NET Core: The best of the new bits
ASP.NET Core: The best of the new bitsASP.NET Core: The best of the new bits
ASP.NET Core: The best of the new bits
 
.NET Core: a new .NET Platform
.NET Core: a new .NET Platform.NET Core: a new .NET Platform
.NET Core: a new .NET Platform
 
Introduction to Containers & Diving a little deeper into the benefits of Con...
 Introduction to Containers & Diving a little deeper into the benefits of Con... Introduction to Containers & Diving a little deeper into the benefits of Con...
Introduction to Containers & Diving a little deeper into the benefits of Con...
 
White Paper : ASP.NET Core AngularJs 2 and Prime
White Paper : ASP.NET Core AngularJs 2 and PrimeWhite Paper : ASP.NET Core AngularJs 2 and Prime
White Paper : ASP.NET Core AngularJs 2 and Prime
 
.NET Core, ASP.NET Core Course, Session 1
.NET Core, ASP.NET Core Course, Session 1.NET Core, ASP.NET Core Course, Session 1
.NET Core, ASP.NET Core Course, Session 1
 
Asp.NETZERO - A Workshop Presentation by Citytech Software
Asp.NETZERO - A Workshop Presentation by Citytech SoftwareAsp.NETZERO - A Workshop Presentation by Citytech Software
Asp.NETZERO - A Workshop Presentation by Citytech Software
 
Introduction to dot net
Introduction to dot netIntroduction to dot net
Introduction to dot net
 
AWS Summit Auckland - Moving MS .NET Applications One Container at a Time
AWS Summit Auckland - Moving MS .NET Applications One Container at a TimeAWS Summit Auckland - Moving MS .NET Applications One Container at a Time
AWS Summit Auckland - Moving MS .NET Applications One Container at a Time
 
Ow
OwOw
Ow
 
Moving microsoft .net applications one container at a time
 Moving microsoft .net applications one container at a time  Moving microsoft .net applications one container at a time
Moving microsoft .net applications one container at a time
 
.NET Core, ASP.NET Core Course, Session 18
 .NET Core, ASP.NET Core Course, Session 18 .NET Core, ASP.NET Core Course, Session 18
.NET Core, ASP.NET Core Course, Session 18
 
Developing Applications on AWS with .NET Core - DEV330 - re:Invent 2017
Developing Applications on AWS with .NET Core - DEV330 - re:Invent 2017Developing Applications on AWS with .NET Core - DEV330 - re:Invent 2017
Developing Applications on AWS with .NET Core - DEV330 - re:Invent 2017
 
Short-Training asp.net vNext
Short-Training asp.net vNextShort-Training asp.net vNext
Short-Training asp.net vNext
 
SOLID Programming with Portable Class Libraries
SOLID Programming with Portable Class LibrariesSOLID Programming with Portable Class Libraries
SOLID Programming with Portable Class Libraries
 
ASP.NET vNext
ASP.NET vNextASP.NET vNext
ASP.NET vNext
 
Full session asp net mvc vs aspnet core
Full session asp net mvc vs aspnet coreFull session asp net mvc vs aspnet core
Full session asp net mvc vs aspnet core
 
Introduction to ASP.NET 5
Introduction to ASP.NET 5Introduction to ASP.NET 5
Introduction to ASP.NET 5
 
Pottnet Meetup Essen - ASP.Net Core
Pottnet Meetup Essen - ASP.Net CorePottnet Meetup Essen - ASP.Net Core
Pottnet Meetup Essen - ASP.Net Core
 
Pottnet MeetUp Essen - ASP.Net Core
Pottnet MeetUp Essen - ASP.Net CorePottnet MeetUp Essen - ASP.Net Core
Pottnet MeetUp Essen - ASP.Net Core
 
Unboxing ASP.NET Core
Unboxing ASP.NET CoreUnboxing ASP.NET Core
Unboxing ASP.NET Core
 

Recently uploaded

Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 

Recently uploaded (20)

Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 

Asp.Net Core MVC , Razor page , Entity Framework Core

  • 2. Prerequisite - Dependency injection (DI) • Dependency injection (DI) is a technique for achieving loose coupling between objects and their collaborators, or dependencies. Rather than directly instantiating collaborators, or using static references, the objects a class needs in order to perform its actions are provided to the class in some fashion. • Most often, classes will declare their dependencies via their constructor, allowing them to follow the Explicit Dependencies Principle. This approach is known as "constructor injection"
  • 3. Prerequisite - Dependency Inversion Principle (DIP) • The Dependency Inversion Principle (DIP) states that high level modules should not depend on low level modules; both should depend on abstractions (typically interfaces). Abstractions should not depend on details. • Details should depend upon abstractions which are provided to them when the class is constructed.
  • 4. Prerequisite - containers • A container is essentially a factory that's responsible for providing instances of types that are requested from it. • When a system is designed to use DI, with many classes requesting their dependencies via their constructor (or properties), it's helpful to have a class dedicated to creating these classes with their associated dependencies. These classes are referred to as containers, or more specifically, Inversion of Control (IoC) containers or Dependency Injection (DI) containers.
  • 5. What is ASP.NET Core? • A new free, open-source, high-performance and cross-platform framework for building modern cloud-based Web applications using .NET • ASP.NET Core is a modular framework distributed as NuGet packages. This allows us to include packages that are required in our application.
  • 6. ASP.NET Core • ASP.NET Core is designed to be deployed on cloud as well as on- premises. Developers can now build cloud-based web applications, IoT (Internet of Thing) and mobile backend applications using ASP.NET Core framework which can run on Windows, Linux, and Mac operating systems. • ASP.NET Core Version History Version Release Date ASP.NET Core 2.0 August 2017 ASP.NET Core 1.1 November 2016 ASP.NET Core 1.0 June 2016
  • 7. .NET Core != ASP.NET Core • ASP.NET Core and .NET Core are not the same. They are different, just like ASP.NET and .NET Framework are different. • .NET Core is a fast, lightweight, modular and open source framework for creating web applications and services that run on Windows, Linux and Mac. So, it is a platform on which ASP.NET Core application runs. • .NET Core is named "Core" because it includes core features of the .NET framework.
  • 8. .NET Core components • ASP.NET Core is a part of .NET Core SDK so you don't need to install ASP.NET Core separately. • .NET Core comes under Apache 2 licenses. Visit .NET Core repository on Github to contribute or download the source code.
  • 9. Why ASP.NET Core? • Supports Multiple Platforms: ASP.NET Core applications can run on Windows, Linux, and Mac. So you don't need to build different apps for different platforms using different frameworks. • Fast - 8x Faster than Node; 3x Faster than Go .. ASP.NET Core no longer depends on System.Web.dll for browser-server communication. ASP.NET Core allows us to include packages which we need for our application. This reduces the request pipeline and improves the performance and scalability. • IoC Container: It includes built-in IoC container for automatic dependency injection which makes it maintainable and testable. • Open-Source with Contributions – even the docs
  • 10. Why ASP.NET Core? • Integration with Modern UI Frameworks: It allows you to use and manage modern UI frameworks such as AngularJS, ReactJS, Umber, Bootstrap etc. using Bower (a package manager for the web). • Smaller Deployment Footprint: ASP.NET Core application runs on .NET Core which is smaller than full .NET Framework. So, the application which uses only a part of .NET CoreFX will have smaller deployment size. This reduces the deployment foot print. • Hosting: ASP.NET Core web application can be hosted on multiple platforms with any web server such as IIS, Apache etc. It is not dependent only on IIS as a standard .NET Framework. • Choice of Tools and Editors – Any Text Editor plus CLI, or Visual Studio
  • 11. .NET Core 2.0 -Supported OS versions
  • 12. ASP.NET Core ASP.NET Build for Windows, macOS, or Linux Build for Windows Razor Pages is the recommended approach to create a Web UI as of ASP.NET Core 2.x. See also MVC, Web API, and SignalR. Use Web Forms, SignalR, MVC, Web API, or Web Pages Develop with Visual Studio, Visual Studio for Mac, or Visual Studio Code using C# or F# Develop with Visual Studio using C#, VB, or F# Higher performance than ASP.NET Good performance Choose .NET Framework or .NET Core runtime Use .NET Framework runtime
  • 14. .NET Core Runtime • .NET Core SDK can be installed on the platform you are using such as Windows, Linux or Mac. • .NET Core Runtime and .NET Core SDK are different things. • .NET Core Runtime is only used to run .NET Core application whereas .NET Core SDK includes tools and libraries to develop .NET Core applications.
  • 15. Getting the Bits • Install SDK https://www.microsoft.com/net/download/core • Optional: Install Visual Studio 2017 Install VS2017 .NET Core 2.0 Tools • Confirm Version:
  • 17. Command-line Interface (CLI) • If you do not use Visual Studio for .NET core application development for some reason and want to use different IDE then you can use command-line interface to create, compile, build, restore and run .NET Core application. • .NET Core SDK installation also installs command-line interface for the selected platform. It installs the latest stable version of the tools and put them on your PATH so you can run dotnet from the Console. • .NET Core command-line interface (CLI) tools https://docs.microsoft.com/en-us/dotnet/core/tools/?tabs=netcore2x • Getting started with .NET Core using the command line https://docs.microsoft.com/en-us/dotnet/core/tutorials/using-with-xplat-cli
  • 19. File > New Project > Web • ASP .NET Core Web App • Web App (4.x)
  • 20. Select a Template 1.0 , 1.1, 2.0 Templates • Empty • Web API • Web App (Razor) • Web App (MVC) • Angular • React.js • React.js & Redux Other settings: • Authentication • Docker Support
  • 21. ASP.NET Core Project Structure (Empty Project ) We can change it to folder view by clicking Solution and Folders icon. ASP.NET Core project files and folders are synchronized with physical files and folders.
  • 22. Dependencies • The Dependencies in the ASP.NET Core 2.0 project contain all the installed server-side NuGet packages as well as client-side frameworks such as jQuery, AngularJS, Bootstrap etc. These client- side dependencies are managed using Bower in Visual Studio.
  • 23. Bower “A package manager for the web” • Bower calls itself "A package manager for the web". Within the .NET ecosystem, it fills the void left by NuGet's inability to deliver static content files • New projects created with the ASP.NET Core project templates set up the client-side build process. jQuery and Bootstrap are installed, and Bower is supported. • Client-side packages are listed in the bower.json file. The ASP.NET Core project templates configures bower.json with jQuery, jQuery validation, and Bootstrap.
  • 24. Properties • The Properties node includes launchSettings.json file which includes Visual Studio profiles of debug settings. The following is a default launchSettings.json file. Edit debug settings from the debug tab of project properties. Right click on the project -> select Properties -> click Debug tab.
  • 26. wwwroot • wwwroot folder is treated as a web root folder. Static files can be stored in any folder under the web root and accessed with a relative path to that root. • only files that are in wwwroot folder can be served over an http request. All other files are blocked and cannot be served by default.
  • 27. wwwroot • Generally, there should be separate folders for the different types of static files such as JavaScript, CSS, Images, library scripts etc • You can access static files with base URL and file name. For example, we can access site.css file in the css folder by http://localhost:<port>/css/app.css. • you need to include a middleware for serving static files in the Configure method of Startup.cs.
  • 28. Program.cs • ASP.NET Core web application is actually a console project which starts executing from the entry point public static void Main() in Program class where we can create a host for the web application. • The steps for creating a host in ASP.NET Core 1.x is different in ASP.NET Core 2.x.
  • 30. • The WebHostBuilder class is the helper class to create and configure a host for a web application. • The UseKestrel() method is an extension method which specifies Kestrel as an internal web server. • The Kestrel is an open-source, cross-platform web server for ASP.NET Core. It is designed to be used behind proxy because it has not yet matured to be exposed as a full-fledge web server. • ASP.NET Core application can be a cross-platform application so it can be used with any web server, and not only IIS. • There will be an external web server such as IIS, Apache, Nginx etc. which will dispatch http requests to the internal web server Kestrel.
  • 31. • The UseContentRoot() method specifies the current directory as a root directory which will be src folder in the default ASP.NET Core project. • The UseIISIntegration() method specifies the IIS as the external web server or the reverse proxy server. • The UseStartup<startup>() method specifies the Startup class to be used by the web host. Startup class is like Global.asax of .NET framework where you can configure request pipeline (middleware). • The Build() method returns an instance of IWebHost using the configuration specified above. • The Run() method starts the web application and blocks the calling thread till the host is shutdown The command line application will become web application from this point onwards.
  • 33. Startup Class • ASP.NET Core application must include Startup class. It is like Global.asax in the traditional .NET application. • Startup class includes two public methods ConfigureServices and Configure.
  • 34. Startup ConfigureServices • The Dependency Injection pattern is used heavily in ASP.NET Core architecture. • ConfigureServices includes built-in IoC container to provide dependent objects using constructors. • you can register your dependent classes with the built-in IoC container using IServiceCollection. • After registering dependent class, it can be used anywhere in the application. You just need to include it in the parameter of the constructor of a class where you want to use it. The IoC container will inject it automatically. • You can Configure third-party container like StructureMap, Unity, Autofac, Ninject, Castle Windsor, etc.
  • 35. Dependency Injection in ASP.NET Core • ASP.NET Core is designed from scratch to support Dependency Injection. • ASP.NET Core injects objects of dependency classes through constructor or method by using built-in IoC container. • The built-in container is represented by IServiceProvider implementation that supports constructor injection by default. The types (classes) managed by built-in IoC container is called services. • Framework Services: Services which are a part of ASP.NET Core framework such as IApplicationBuilder, IHostingEnvironment, ILoggerFactory etc. • Application Services: The services (custom types or classes) which you as a programmer create for your application.
  • 37. Service lifetimes and registration options • Transient Transient lifetime services are created each time they're requested. This lifetime works best for lightweight, stateless services. • Scoped Scoped lifetime services are created once per request. • Singleton Singleton lifetime services are created the first time they're requested (or when ConfigureServices is run if you specify an instance there) and then every subsequent request will use the same instance.
  • 38. Startup.Configure • The Configure method is a place where you can configure application request pipeline for your application using IApplicationBuilder instance that is provided by the built-in IoC container. • ASP.NET Core introduced the middleware components to define a request pipeline, which will be executed on every request. • You include only those middleware components which are required by your application and thus increase the performance of your application. • At run time, the ConfigureServices method is called before the Configure method. This is so that you can register your custom service with the IoC container which you may use in the Configure method.
  • 39. Middleware “Built-in and Custom” A middleware is nothing but a component (class) which is executed on every request in ASP.NET Core application. It can be either framework provided middleware, added via NuGet or your own custom middleware. • Each component in the pipeline is a request delegate. • Each delegate can invoke the next component in the chain, or short- circuit, returning back up the call chain
  • 40.
  • 41. ASP.NET Core Request Processing
  • 42. built-in middleware Middleware Description Authentication Adds authentication support. CORS Configures Cross-Origin Resource Sharing. Routing Adds routing capabilities for MVC Session Adds support for user session. StaticFiles Adds support for serving static files and directory browsing. Diagnostics Adds support for reporting and handling exceptions and errors. MVC Adds support for using MVC pattern
  • 43. Diagnostics Middleware Middleware Extension Method Description DeveloperExceptionPageMiddleware UseDeveloperExceptionPage() Captures synchronous and asynchronous exceptions from the pipeline and generates HTML error responses. ExceptionHandlerMiddleware UseExceptionHandler() Catch exceptions, log them and re- execute in an alternate pipeline. StatusCodePagesMiddleware UseStatusCodePages() Check for responses with status codes between 400 and 599. WelcomePageMiddleware UseWelcomePage() Display Welcome page for the root path.
  • 44. Creating Middleware in Startup: Run
  • 45. Creating Middleware in Startup: Use
  • 46. Creating Middleware in Startup: Map
  • 48. UseStaticFiles Middleware • For the wwwroot folder app.UseStaticFiles(); • For your own folder app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), “your own folder path")), RequestPath = "/StaticFiles“ // URLrequest path });
  • 51. appsettings.json - project.json • The project.json file includes settings for an application which is used by .NET Core CLR (runtime) to determine how to run an application.
  • 52. Choose Profile While Debugging
  • 53. Install Entity Framework Core https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/new-db
  • 54. Working With a Database Using EF Core • Add Entity Framework Core (EF Core) in ConfigureServices: • Also supports InMemory – Install this package: and modify ConfigureServices:
  • 55. Working with EF Core’s AppDbContext • Never directly instantiate your application’s DbContext type(s) • Instead, request from DI using constructor parameters Recommendation • Follow the Dependency Inversion Principle and avoid having UI types depend on details • Using Entity Framework Core is an implementation detail • Instead depend on an abstraction over your persistence method • Common pattern for this: Repository
  • 57. Razor Pages • Razor Pages is an exciting new product released with ASP.NET Core 2, which makes building webpages without an MVC framework quick and easy. • Razor Pages is a new feature of ASP.NET Core that makes coding page-focused scenarios easier and more productive. • The most importantly thing to know about Razor Pages is that they are built on top of ASP.NET Core MVC, not beside it, and so all the goodness from ASP.NET MVC applications (routing, ModelState, etc.) you can still access in Razor Pages apps.
  • 58. Razor Pages • All of the Razor Pages types and features live in the Microsoft.AspNetCore.Mvc.RazorPages assembly. • The MVC package – Microsoft.AspNetCore.Mvc includes the Razor Pages assembly. • That means that you can use Razor Pages out of the box with MVC.
  • 59. HOW? • If you want to build few simple pages with MVC, you have controller actions in separate place, HTML for view in separate place, ViewModel in a different location, routes in separate place, and that just seems like too much. • With Razor Pages, you have this one Razor file (.cshtml), and the code for a single page lives inside of that file, and that file also represents the URL structure of the app . Therefore, you got everything inside of one file, and it just works. • However, you CAN separate your code to the code behind file with .cshtml.cs extension. You would usually have your view model and handlers (like action methods in MVC) in that file and handle the logic there.
  • 60. Creating Razor Pages app • With VS 2017 and .NET Core 2 SDK installed if we follow the old standard path in Visual Studio: File -> New Project -> Web -> ASP.NET Core Web Application we will get the following screen:
  • 61. Project files and folders File or folder Purpose wwwroot Contains static files. See Work with static files. Pages Folder for Razor Pages. appsettings.json Configuration Program.cs Hosts the ASP.NET Core app. Startup.cs Configures services and the request pipeline. See Startup.
  • 62. The Pages folder • The _Layout.cshtml file contains common HTML elements (scripts and stylesheets) and sets the layout for the application. • The _ViewStart.cshtml sets the Razor Pages Layout property to use the _Layout.cshtml file. • The _ViewImports.cshtml file contains Razor directives that are imported into each Razor Page. • The _ValidationScriptsPartial.cshtml file provides a reference to jQuery validation scripts. • The About, Contact and Index pages are basic pages you can use to start an app. The Error page is used to display error information.
  • 63. Configure bundling and minification • The MVC and Razor Pages project templates provide a bundleconfig.json configuration file which defines the options for each bundle. • By default, a single bundle configuration is defined for the custom JavaScript (wwwroot/js/site.js) and stylesheet (wwwroot/css/site.css) files • https://docs.microsoft.com/en-us/aspnet/core/client-side/bundling- and-minification
  • 64. Razor Pages is enabled in Startup.cs:
  • 65. @page Directive • @page makes the file into an MVC action - which means that it handles requests directly, without going through a controller. • @page must be the first Razor directive on a page. • the PageModel class file has the same name as the Razor Page file with .cs appended
  • 66. Determine URL paths to pages • The associations of URL paths to pages are determined by the page's location in the file system. • The runtime looks for Razor Pages files in the Pages folder by default. • Index is the default page when a URL doesn't include a page. File name and path matching URL /Pages/Index.cshtml / or /Index /Pages/Contact.cshtml /Contact /Pages/Store/Contact.cshtml /Store/Contact /Pages/Store/Index.cshtml /Store or /Store/Index
  • 67. URL generation for Pages -Example • URL generation for pages supports relative names. • The following table shows which Index page is selected with different RedirectToPage parameters from Pages/Customers/Create.cshtml RedirectToPage(x) Page RedirectToPage("/Index") Pages/Index RedirectToPage("./Index"); Pages/Customers/Index RedirectToPage("../Index") Pages/Index RedirectToPage("Index") Pages/Customers/Index RedirectToPage("Index"), RedirectToPage("./Index"), and RedirectToPage("../Index") are relative names. The RedirectToPage parameter is combined with the path of the current page to compute the name of the destination page.
  • 68. PageModel • the PageModel class is called <PageName>Model and is in the same namespace as the page. • The PageModel class allows separation of the logic of a page from its presentation. • It defines page handlers for requests sent to the page and the data used to render the page. • You can add handler methods for any HTTP verb. The most common handlers are: • OnGet to initialize state needed for the page. • OnPost to handle form submissions.
  • 69. [BindProperty] • Razor Pages, by default, bind properties only with non-GET verbs. Binding to properties can reduce the amount of code you have to write. Binding reduces code by using the same property to render form fields. • To bind a property on GET requests, set the [BindProperty] attribute's Supports Get property to true: [BindProperty(SupportsGet = true)]
  • 70. Customizing Routing - @page "{id:int}" • The routing constraint"{id:int}" tells the page to accept requests to the page that contain int route data. • If a request to the page doesn't contain route data that can be converted to an int, the runtime returns an HTTP 404 (not found) error. • To make the ID optional, append ? to the route constraint: @page "{id:int?}"
  • 71. Multiple handlers per page • The asp-page-handler attribute is a companion to asp-page. asp- page-handler generates URLs that submit to each of the handler methods defined by a page. The preceding code uses named handler methods. Named handler methods are created by taking the text in the name after On<HTTP Verb> and before Async (if present)
  • 72. Configuration and settings • you can use the RazorPagesOptions to set the root directory for pages, or add application model conventions for pages.
  • 73. Custom root directory • Add WithRazorPagesRoot to AddMvc to specify that your Razor Pages are at a custom root directory in the app (provide a relative path):
  • 74. Browser Link in ASP.NET Core • Browser Link is a feature in Visual Studio that creates a communication channel between the development environment and one or more web browsers. You can use Browser Link to refresh your web application in several browsers at once, which is useful for cross- browser testing. • Configuration In the Configure method of the Startup.cs file: app.UseBrowserLink();
  • 75. How to use Browser Link From the Browser Link toolbar control, you can: • Refresh the web application in several browsers at once. • Open the Browser Link Dashboard. • Enable or disable Browser Link. Note: Browser Link is disabled by default in Visual Studio 2017 (15.3). • Enable or disable CSS Auto-Sync.
  • 76. Open multiple browsers at once To open multiple browsers at once, choose Browse with... from the same drop-down. Hold down the CTRL key to select the browsers you want, and then click Browse
  • 77. Enable or disable CSS Auto-Sync • When CSS Auto-Sync is enabled, connected browsers are automatically refreshed when you make any change to CSS files. How does it work? Browser Link uses SignalR to create a communication channel between Visual Studio and the browser. When Browser Link is enabled, Visual Studio acts as a SignalR server that multiple clients (browsers) can connect to. Browser Link also registers a middleware component in the ASP.NET request pipeline. This component injects special <script> references into every page request from the server.
  • 78. Tag Helpers • Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files. • Replaces HTML Helpers (still available, but not recommended) • Render within HTML tags • A rich IntelliSense environment for creating HTML and Razor markup • There are many built-in Tag Helpers for common tasks - such as creating forms, links, loading assets and more • @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers • https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built- in/index?view=aspnetcore-2.0
  • 79. Managing Tag Helper scope • Tag Helpers scope is controlled by a combination of @addTagHelper, @removeTagHelper, and the "!" opt-out character. • @addTagHelper makes Tag Helpers available. • @removeTagHelper removes Tag Helpers. • You can disable a Tag Helper at the element level with the Tag Helper opt-out character ("!") <!span asp-validation-for="Email" class="text-danger"></!span>
  • 80. IntelliSense support for Tag Helpers • When you create a new ASP.NET web app in Visual Studio, it adds the NuGet package "Microsoft.AspNetCore.Razor.Tools". This is the package that adds Tag Helper tooling
  • 82. Author Tag Helpers • A tag helper is any class that implements the ITagHelper interface. However, when you author a tag helper, you generally derive from TagHelper, doing so gives you access to the Process method. • Add the yourTagHelper class to the TagHelpers folder. • To make the yourTagHelper class available to all our Razor views, add the addTagHelper directive to the Views/_ViewImports.cshtml .
  • 83. Razor Pages • Razor Pages are Page focused way of programming web sites • You can(if you want to) have all the code and HTML in one place • The location of Razor page file determines the URL/route for your page • Razor Pages are not a reincarnation of old ASP.NET Web Pages • Features that we can use with MVC we can also use with Razor Pages: • Model Binding • Razor support • Tag Helpers • HTML Helpers • Handlers (Action Methods) • etc.. • We have handlers (OnGet, OnGetAsync, OnPostAsync etc..) • Location of the page in file system (project structure) determines the URL path • Need to have one root folder • Stored in Pages root folder by default (configurable)
  • 85. ASP.NET Core MVC with EF Core • EF Core 2.0 is the latest version of EF but doesn't yet have all the features of EF 6.x. • To add EF Core support to a project, install the database provider that you want to target. This tutorial uses SQL Server, and the provider package is Microsoft.EntityFrameworkCore.SqlServer. This package is included in the Microsoft.AspNetCore.All metapackage, so you don't have to install it. • This package and its dependencies (Microsoft.EntityFrameworkCore and Microsoft.EntityFrameworkCore.Relational) provide runtime support for EF.
  • 86. Install Entity Framework Core https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/new-db
  • 87. Working With a Database Using EF Core • Add Entity Framework Core (EF Core) in ConfigureServices: • Also supports InMemory – Install this package: and modify ConfigureServices:
  • 88. Using EF Core’s AppDbContext • 1- install Entity Framework Core NuGet packages. • 2- Create the data model • 3- Create the Database Context • 4-Add your connection string in appsettting.json • 5- Register the context with dependency injection • 6-Add Migration and Update Database.
  • 89. Working with EF Core’s AppDbContext • Never directly instantiate your application’s DbContext type(s) • Instead, request from DI using constructor parameters Recommendation • Follow the Dependency Inversion Principle and avoid having UI types depend on details • Using Entity Framework Core is an implementation detail • Instead depend on an abstraction over your persistence method • Common pattern for this: Repository
  • 90. Loading Related Data Entity Framework Core allows you to use the navigation properties in your model to load related entities. There are three common O/RM patterns used to load related data. • Eager loading means that the related data is loaded from the database as part of the initial query. • Explicit loading When the entity is first read, related data isn't retrieved. You write code that retrieves the related data if it's needed. • Lazy loading When the entity is first read, related data isn't retrieved. However, the first time you attempt to access a navigation property, the data required for that navigation property is automatically retrieved.
  • 91. Eager loading • You can use the Include method to specify related data to be included in query results. • You can include related data from multiple relationships in a single query.
  • 92. Including multiple levels -Eager loading • You can drill down thru relationships to include multiple levels of related data using the ThenInclude method. • Note: Visual Studio offer incorrect code completion options when using the ThenInclude This is a symptom of an IntelliSense bug . It is safe to ignore these spurious syntax errors as long as the code is correct and can be compiled successfully.
  • 93. Explicit loading • This feature was introduced in EF Core 1.1. • When the entity is first read, related data isn't retrieved. You write code that retrieves the related data if it's needed. • you can use the Load method to do explicit loading.
  • 94. Lazy loading • This feature was introduced in EF Core 2.1. • The simplest way to use lazy-loading is by installing the Microsoft.EntityFrameworkCore.Proxies package and enabling it with a call to UseLazyLoadingProxies when using AddDbContext: EF Core will then enable lazy-loading for any navigation property that can be overridden--that is, it must be virtual and on a class that can be inherited from.
  • 95. Performance considerations • If you know you need related data for every entity retrieved, eager loading often offers the best performance, because a single query sent to the database is typically more efficient than separate queries for each entity retrieved. • In some scenarios separate queries is more efficient. Eager loading of all related data in one query might cause a very complex join to be generated, which SQL Server can't process efficiently.
  • 96. Repository Pattern In ASP.NET Core MVC And Entity Framework Core The repository pattern is intended to create an Abstraction layer between the Data Access layer and Business Logic layer of an Application. It is a data access pattern that prompts a more loosely coupled approach to data access. We create a generic repository, which queries the data source for the data, maps the data from the data source to a business entity and persists changes in the business entity to the data source
  • 97. WHY? • We implement repository pattern to develop a loosely coupled application. It makes the code more testable. It creates an abstraction layer between ORM and business logic layer of the application. • the repository mediates between the data source layer (Entity Framework) and the business layer (Controller) of the application. It performs operations as following way. • It queries the underlying data source (database) for the data. • It maps the data from the data source to a business entity that uses to create the database. • It persists changes in the business entity to the data source.
  • 98. Advantages of Repository Pattern It has some advantages which are as follows: • An entity might have many operations which perform from many locations in the application, so we write logic for common operations in the repository. These operations might be Create, Read, Update, Delete, Search, Filter, Sort, Paging, and Caching etc. • The Entity Framework is not testable out of the box. We have to create mock classes to test it. Data access logic can be tested using repository pattern. • As business logic and data access logic separate in the repository pattern that’s why it easy to manage and readable. It reduces development as well me, as common functionality logic writes once in the application.
  • 99. How? “Employee Entity” • ASP.NET Core is designed to support dependency injection. So, we create a repository interface named IEmployeeRepository for Employee . • This interface has definitions of all methods to perform CRUD operations on the Employee entity. • let’s implement the preceding interface on a class named EmployeeRepository. • This class has implemention of all methods to perform CRUD operations on the Employee entity. It has a parameterized constructor that accepts Context as a parameter. It passes at a time of repository instance creates by dependency injection.
  • 100. How? “Employee Entity” cont.. • web application communicates to data access layer via an interface so we register repository to the dependency injection during the application start up. • Create Application User Interface • create a view model named EmployeeViewModel for application UI and CRUD operations. This model strongly binds with a view.
  • 101. Routing to controller actions in ASP.NET Core • Actions are either conventionally routed or attribute routed. Placing a route on the controller or the action makes it attribute routed. • With attribute routing the controller name and action names play no role in which action is selected.
  • 102. Attribute routing with Http[Verb] attributes. • Attribute routing can also make use of the Http[Verb] attributes such as HttpPostAttribute. All of these attributes can accept a route template.
  • 103. Token replacement in route templates • For convenience, attribute routes support token replacement by enclosing a token in square-braces ([, ]). • No route Prefix.
  • 105. Specifying attribute route optional parameters, default values, and constraints • {id:int} integar constraint. • {id:int?} optional Parameter • {id:int=3} Default Value
  • 106. IActionResult there are a wide range of ways that you can return content from MVC controllers that aren't limited to just ActionResults. • ContentResult • EmptyResult • FileResult • HttpStatusCodeResult • JavaScriptResult • JsonResult • RedirectResult • RedirectToRouteResult
  • 107. View components in ASP.NET Core • New to ASP.NET Core MVC, view components are similar to partial views, but they're much more powerful. View components don't use model binding, and only depend on the data provided when calling into it. A view component: • Renders a chunk rather than a whole response. • Includes the same separation-of-concerns and testability benefits found between a controller and view. • Can have parameters and business logic. • Is typically invoked from a layout page.
  • 108. Using of View components View components are intended anywhere you have reusable rendering logic that's too complex for a partial view. • Dynamic navigation menus • Tag cloud (where it queries the database) • Login panel • Shopping cart • Recently published articles • Sidebar content on a typical blog • A login panel that would be rendered on every page and show either the links to log out or log in, depending on the log in state of the user
  • 109. Creating a view component • A view component class can be created by Deriving from ViewComponent class. • A view component defines its logic in an InvokeAsync method that returns an IViewComponentResult. • Parameters come from the calling method, not HTTP, there's no model binding • The runtime searches for the view in the following paths: • Views/<controller_name>/Components/<view_component_name>/<view_name> • Views/Shared/Components/<view_component_name>/<view_name> • The default view name for a view component is Default, which means your view file will typically be named Default.cshtml. • We recommend you name the view file Default.cshtml and use the Views/Shared/Components/<view_component_name>/<view_name> path.
  • 110. Invoking a view component • To use the view component, call the following inside a view: • Invoking a view component as a Tag Helper In order to use a View Component as a Tag Helper, you must register the assembly containing the View Component using the @addTagHelper directive if your View Component is in an assembly called "MyWebApp", add the following directive to the _ViewImports.cshtml file:@addTagHelper *, MyWebApp
  • 111. Tag Helpers • Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files. • Replaces HTML Helpers (still available, but not recommended) • Render within HTML tags • A rich IntelliSense environment for creating HTML and Razor markup • There are many built-in Tag Helpers for common tasks - such as creating forms, links, loading assets and more • @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers • https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built- in/index?view=aspnetcore-2.0
  • 112. Managing Tag Helper scope • Tag Helpers scope is controlled by a combination of @addTagHelper, @removeTagHelper, and the "!" opt-out character. • @addTagHelper makes Tag Helpers available. • @removeTagHelper removes Tag Helpers. • You can disable a Tag Helper at the element level with the Tag Helper opt-out character ("!") <!span asp-validation-for="Email" class="text-danger"></!span>
  • 113. IntelliSense support for Tag Helpers • When you create a new ASP.NET web app in Visual Studio, it adds the NuGet package "Microsoft.AspNetCore.Razor.Tools". This is the package that adds Tag Helper tooling
  • 115. Author Tag Helpers • A tag helper is any class that implements the ITagHelper interface. However, when you author a tag helper, you generally derive from TagHelper, doing so gives you access to the Process method. • Add the yourTagHelper class to the TagHelpers folder. • To make the yourTagHelper class available to all our Razor views, add the addTagHelper directive to the Views/_ViewImports.cshtml .
  • 116. References • ASP .NET: http://www.asp.net • .NET Core: https://www.microsoft.com/net • .NET Web Dev Blog: https://blogs.msdn.microsoft.com/webdev • Scott Hanselman’s Blog: https://www.hanselman.com/blog • .NET Conf: http://www.dotnetconf.net • MSDN Channel 9: https://channel9.msdn.com • Tutorials: https://docs.microsoft.com/en-us/aspnet/core/tutorials/first- mvc-app • C# 7: https://docs.microsoft.com/en-us/dotnet/articles/csharp/csharp-7 • ASP.NET Core Roadmap: https://github.com/aspnet/Home/wiki/Roadmap
  • 117. References • New Razor Pages: http://www.hishambinateya.com/welcome-razor-pages • Intro to Razor: https://docs.microsoft.com/en-us/aspnet/core/mvc/razor- pages • Migrating from MVC to MVC Core: https://docs.microsoft.com/enus/aspnet/core/migration/mvc • .NET core : https://mva.microsoft.com/learning-path/aspnet-core-20- 23?MC=ASPNET • Repository Pattern in ASP.Net Core mvc : http://l-knowtech.com/2017/09/12/repository-pattern-asp-net-core-mvc- entity-framework-core/
  • 118. References Try ASP.NET Core course: https://www.codeschool.com/courses/try-asp-net-core ASP.NET CoreQuick Start : http://aspnetcorequickstart.com/ Razor Pages : http://www.dotnet-stuff.com/tutorials/aspnet-core/introduction-to-razor-pages-in- asp-net-core Introduction to ASP.NET Core Razor Pages - Damian Edwards: https://www.youtube.com/watch?v=yyBijyCI5Sk Simpler ASP.NET Apps with Razor Pages : https://msdn.microsoft.com/en-us/magazine/mt842512.aspx