SlideShare a Scribd company logo
© Copyright SELA Software & Education Labs Ltd. | 14-18 Baruch Hirsch St Bnei Brak, 51202 Israel | www.selagroup.com
Ido Flatow
Getting to Know ASP.NET 5 and MVC 6
Agenda
Introduction to ASP.NET 5
What’s new in ASP.NET 5
ASP.NET MVC 6
About Me
Senior Architect, Sela Group
Microsoft Regional Director, and an ASP.NET/IIS MVP
Co-author of courses and books
Focus on server, web, and cloud
Manager of the Israeli Web Developers User Group
History of ASP (18 years)
1996 - Active Server Pages (ASP)
2002 – ASP.NET
2008 – ASP.NET MVC
2010 – ASP.NET Web Pages
2012 – ASP.NET Web API, SignalR
2014 – ASP.NET vNext
Current ASP.NET stack
Windows Server
IIS
.NET Framework
ASP.NET
Web
Forms
MVC Web API
System.Web
HTTP
Modules
HTTP
Handlers
Request
Pipeline
Caching
Session
State
Problems with ASP.NET architecture
Limited hosting possibilities (IIS only)
Dependency on IIS environment (System.Web)
Web evolves faster than .NET framework
Requires full-blown .NET framework - resource
intensive and not web-friendly
Hard to optimize for lightweight high-
performance apps
Introducing ASP.NET 5 stack
OS
.NET CLR
ASP.NET
Web API MVC Web Pages
Host
IIS Self-hosted
.NET Core CLR
Middleware
.NET 2015: High-Level Overview
.NET Framework 4.6
.NET Core & App Models
Caution
At the time of this presentation, we are using
DNX-CLR-x86 1.0.0-beta4 (ASP.NET 5 beta 4)
As things are moving really fast in this new
world, it’s very likely that the things explained
here will slightly change
ASP.NET 5 – Agility
Faster Development Cycle
Features are shipped as packages
Framework ships as part of the application
More Control
Zero day security bugs patched by Microsoft
Same code runs in development and production
Developer opts into new versions, allowing breaking
changes
ASP.NET 5 - Fast
Runtime Performance
Faster startup times
Lower memory / higher density (> 90% reduction)
Modular, opt into just features needed
Use a raw socket, framework or both
Development productivity and low friction
Edit code and refresh browser
Flexibility of dynamic environment with the power of
.NET
Develop with Visual Studio, third party and cloud
editors
ASP.NET 5 – Cross Platform
Runtime
Windows, Mac, Linux
Editors
Visual Studio, Text, Cloud editors
OmniSharp – Sublime, Emacs, Vi, etc.
No editors (command line)
All Open Source with Contributions
ASP.NET 5 Features
New flexible and cross-platform runtime
New modular HTTP request pipeline
Robust environment configuration
Unified programming model for MVC API
See changes without re-building the project
Side-by-side versioning of the .NET Framework
Built in Dependency Injection
Ability to self-host or host on IIS
Open source in GitHub
File  New Project  Web
Web App
Class Lib?
Console App?
Select a Template
Startup.cs Configuration
Let's talk about OWIN
Open Web Interface for .NET
Community project (http://owin.org)
Decouples application from server
Enforces modularity of the server
Stack of modules (middlewares) is processing
the request from application to server
Microsoft implementation of OWIN is "Katana"
OWIN Implementation
Host
Middleware
Server
Application
Middleware
Middleware
Request Response
Startup, bootstrapping,
process management
Manages sockets,
delegates to middlewares
Pass-through
components stack
Your code
ASP.NET 5 Middlewares
Improved HTTP performance
New HTTP request pipeline that is lean and fast
The new pipeline also supports OWIN
You choose what to use in your application
By registering middlewares
public void Configure(IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory loggerfactory)
{
app.UseErrorHandler("/Home/Error");
app.UseStaticFiles();
app.UseIdentity();
app.UseMvc(routes => ...)
}
Custom Middleware
Create middleware class
app.UseMiddleware<AppHeaderMiddleware>();
// Register before app.UseMvc(...);
public class AppHeaderMiddleware {
private readonly RequestDelegate next;
public AppHeaderMiddleware(RequestDelegate next) {
this.next = next;
}
public async Task Invoke(HttpContext context) {
context.Response.Headers.Append(
"X-Application", "ASP.NET 5 Sample App");
await this.next.Invoke(context);
}
}
Register in Startup.cs (IApplicationBuilder)
Project.json
Package Management
ASP.NET 5 introduces a new, lightweight way to
manage dependencies in your projects
No more assembly references
Instead referencing NuGet packages
project.json file
Structure of the "project.json" file
Dependencies - lists all the dependencies of your
application (NuGet, source files, etc.)
Configuration - compilation settings (debug,
release)
Frameworks - target frameworks with their
dependencies
Sources - what should be compiled
Web root - server root of the app
Shared files - files shared with dependent projects
Commands - commands available to “dnx”
Scripts - pre/post events to hook scripts to
Metadata - general project information
Right-click  (Project) Properties
Compilation Process
Debugging without Roslyn
Change the
code
C#
Compiler
invoked
Load code
in memory
Execute
the dll
dll loaded
in memory
from File
system
Emits the
dll in file
system
Debugging with Roslyn
Change the
code
Load code
in memory
Code is
Executed in
memory
Roslyn
compiles
code in
memory
Time reduced from 7-8 second to 1-2 second
"K“ / ”DNX” Command Line Tools
KRE / DNX- Runtime Environment
Engine that runs your application (compilation system,
SDK tools, and the native CLR hosts)
KVM / DNVM - Version Manager
Tool for updating and installing different versions of
KRE/DNX
KPM / DNU- Package Manager
Tool to restore and install (NuGet) packages needed by
applications to run
K / DNX
Entry point to the runtime - starts the runtime with
commands
OpenSource
Runtime Loader
IIS: WebEngine4
Exe: OS
DNX
Operating SystemWindows
Windows, OSX,
Linux
Libraries
Loose, GAC,
Nuget
NuGet, NPM,
Bower
App FrameworksFCL, GAC, NuGet NuGet
Web ServerIIS
IIS, HTTP.SYS,
Kestrel
Application HostSystem.Web DNX
Platform Libraries.NET BCL & FCL
.NET BCL & FCL
.NET on Nuget
Runtime.NET CLR
.NET CLR
.NET Core CLR
Application
MSBuild/CodeDom
-> csc.exe
DNX (Roslyn)
Present vs. Future
© Copyright SELA Software & Education Labs Ltd. | 14-18 Baruch Hirsch St Bnei Brak, 51202 Israel | www.selagroup.com
MVC 6
ASP.NET <5 Frameworks
ASP.NET 5 with MVC 6
MVC + Web API + Web Pages =
ASP.NET MVC 6!
ASP.NET MVC 6
No more duplication - one set of concepts
Used for creating both UI and API
Smooth transition from Web Pages to MVC
Based on the new ASP.NET 5 pipeline
Built DI first
Runs on IIS or self-host
Getting Started with MVC 6
Startup.cs
Project.json
app.UseMvc(routes =>
{
routes.MapRoute("default", "{controller}/{action}/{id?}",
new { controller = "Home", action = "Index" });
});
app.UseServices(services => { services.addMvc(); })
"dependencies": {
"Microsoft.AspNet.Server.IIS": "1.0.0-*",
// Add this:
"Microsoft.AspNet.Mvc": "6.0.0-*"
}
Routing Template Improvements
Inline constraints
Product/{ProductId:long}
Product/{ProductName:alpha}
Product/{ProductName:minlength(10)}
Product/{productId:regex(^d{4}$)}
Optional parameters
Product/{productId:long?}
Default values
Product/{productId:long=1}
Available with MapRoute() and [Route()]
https://github.com/aspnet/Routing/tree/dev/src/
Microsoft.AspNet.Routing
Where is the Web API
Configuration?
Route configuration -> attribute-based routing
Message handlers -> middleware pipeline
Filters and Formatters -> startup.cs
app.UseServices(services => {
services.Configure<MvcOptions>(options =>
{
options.AddXmlDataContractSerializerFormatter();
options.Filters.Add(new ValidatorFilterAttribute());
});
}
Controllers – Two Birds, One Stone
API – similar, but different
UI – same as with MVC 5
[Route("api/[controller]")]
public class ProductsController : Controller
{
[HttpGet("{id:int}")]
public Product GetProduct(int id)
{
return new Product() { ID = id };
}
}
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
Actions – API with IActionResult
[HttpGet("{id:int}", Name = "GetByIdRoute")]
public IActionResult GetById (int id)
{
var item = _items.FirstOrDefault(x => x.Id == id);
if (item == null) { return HttpNotFound(); }
return new ObjectResult(item);
}
[HttpPost]
public IActionResult CreateTodoItem([FromBody] TodoItem item)
{
_items.Add(item);
return CreatedAtRoute(
"GetByIdRoute", new { id = item.Id }, item);
}
IActionResult for UI and API
https://github.com/aspnet/Mvc/tree/dev/src/
Microsoft.AspNet.Mvc.Core/ActionResults
UI API
PartialViewResult BadRequestResult
RedirectResult ContentResult
ViewResult CreatedAtRouteResult
JsonResult HttpStatusCodeResult
JsonResult
ObjectResult
ChallengeResult
HttpNotFoundResult
FileContentResult
Content Negotiation
MVC still respects Accept headers
The XML formatter was removed from the MVC 6
pipeline
You can manually add it to the Formatters collection
Forcing a content-type:
Return a JsonResult
Use the [Produces("application/json")] attribute
Additional changes:
Actions returning string result in text/plain responses
Returning null/void – response will be HTTP 204 (no
content)
Last Controller Goodie - DI
Dependency Injection and MVC
ASP.NET 5 is DI-friendly
Basic DI container available throughout the stack
BYOC is also supported (already implemented for
Autofac, Ninject, StructureMap, Unity, and Windsor)
Out-of-the-box container supports
Singleton / Instance – single instance
Transient – new instance each time
Scoped – new instance per request
https://github.com/aspnet/DependencyInjection/tree
/dev/src
Last Controller Goodie - DI
public class ProductsController : Controller
{
private readonly IProductsRepository _repository;
public ProductsController(IProductsRepository repository)
{
this._repository = repository;
}
public IActionResult Index()
{
var products = _repository.GetAllProducts();
return View(products);
}
}
app.UseServices(services =>
{
services.AddTransient<IProductsRepository, DefaultProductsRepository>();
});
Look Ma No Controller
Use the Controller suffix
Inject HTTP request, principal, and view data with:
Convention-based property injection
Constructor injection
public class SimpleController
{
[Activate]
public ActionContext ActionContext { get; set; }
[Activate]
public ViewDataDictionary ViewData { get; set; }
[Activate]
public IUrlHelper Url { get; set; }
public string Get()
{
return "Hello world";
}
}
Enough with Controllers,
What About MVC Views?
Oh, right!
Child Actions in MVC <6
Rendering partial views with controller logic
and model
Do not confuse with Html.Partial
@Html.Action("GetProductDetails", "Products", new { id = 1})
[ChildActionOnly]
public ActionResult GetProductDetails(int id)
{
var product = _repository.GetProduct(id);
return PartialView("ProductDetails", product);
}
Child Actions in MVC 6
So what’s the problem?
Part of a controller, but invoked from a view
Controller flow must distinguish between HTTP calls and
view calls
Pattern lacks an asynchronous invocation
Solution?
Replace child actions with View Components
Same partial views, but declared in a separate class
Think of it as a “mini-controller”
Supports the same DI and POCO features as a controller
Implement actions as synchronous or asynchronous
View Components in MVC 6
//[ViewComponent(Name = "ProductDetails")]
public class ProductDetailsViewComponent : ViewComponent
{
private readonly IProductsRepository _repository;
public ProductDetailsViewComponent(IProductsRepository repository)
{
_repository = repository;
}
public IViewComponentResult Invoke(int id)
{
var product = _repository.GetProduct(id);
return View(product);
}
@Component.Invoke("ProductDetails", 1)
// Or as async, if InvokeAsync is implemented in the view component
@await Component.InvokeAsync("ProductDetails", 1)
And the Partial View?
Create a default.cshtml file
(content structured similar as with MVC <6)
Place file in:
Controller-specific:
Views/{controller}/Components/ProductDetails/Default.cshtml
Shared:
Views/Shared/Components/ProductDetails/Default.cshtml
Customizing view name is supported
Create a file other than Default.cshtml
Return View(viewName, model)
Injecting Services to Views
Preferable than using static classes/methods
Use interfaces instead of concrete types
Register in IoC using different lifecycles
public class CatalogService : ICatalogService
{
public async Task<int> GetTotalProducts() {...} // From ICatalogService
}
@inject MyApp.Services.ICatalogService Catalog
<html>
<body>
<h3>Number of products in the catalog</h3>
@await Catalog.GetTotalProducts()
</body>
</html>
services.AddTransient<ICatalogService, CatalogService>();
Last, but not Least, Tag Helpers
Do this:
Ah? What’s that?
Instead of doing this:
<form asp-anti-forgery="true" asp-action="UpdateProduct">


</form>
using (Html.BeginForm("UpdateProduct", "Products", FormMethod.Post))
{
@Html.AntiForgeryToken()


}
It’s the return of Web Controls, NOOOOOO!!!
Tag Helpers are not Evil
Tag Helpers generate markup only within their
enclosing tag
Less Razor/HTML mess in the .cshtml file
JavaScript directive style approach
Use C# to better construct the markup
Add/remove parts from the inner content
Generate complex HTML (recursive, nested, 
)
Cache the output
Existing Tag Helpers
HTML elements
<a>, <form>, <input>, <label>, <link>, <script>,
<select>, <textarea>
Logical
<cache>
Placeholders
ValidationSummary (<div>), ValidationMessage (<span>)
You can create your own Tag Helpers
Check out the source for reference
https://github.com/aspnet/Mvc/tree/dev/src/Micros
oft.AspNet.Mvc.TagHelpers
Key Improvements in ASP.NET 5
Totally modular
NuGet is first-class citizen in ASP.NET 5
Everything is a package
Lightweight - you use minumum set of modules
Faster startup, lower memory (>90%)
Does not require .NET Framework installation -
runtime environment (CLR) can be deployed
with your application
Key Improvements in ASP.NET 5
Cross platform - can be hosted anywhere:
IIS, self-hosted, Linux, MAC...
Web Forms are left aside for now
Better developer experience
No-compile debugging with Roslyn, MVC unified
programming model, basic DI out-of-the-box...
Everything is open-source
Architecture is OWIN based
Getting Started with ASP.NET 5
Ships with Visual Studio 2015
Walkthroughs and samples at http://asp.net/vnext
Documentation at http://docs.asp.net/en/latest
Get the code from http://github.com/aspnet
Read blogs at http://blogs.msdn.com/b/webdev
Try out a nightly build from MyGet
https://www.myget.org/F/aspnetvnext
My Info
idof@sela.co.il
@idoFlatow
http://bit.ly/flatowblog

More Related Content

What's hot (20)

PPT
WPF
Vishwa Mohan
 
PDF
Angular - Chapter 1 - Introduction
WebStackAcademy
 
PDF
Asp.Net Core MVC , Razor page , Entity Framework Core
mohamed elshafey
 
PDF
CSS
Vladimir Zhidal
 
PDF
Angular
Lilia Sfaxi
 
PDF
Meetup React Sanca - 29/11/18 - React Testing
Augusto Lazaro
 
PPTX
Design Patterns - Abstract Factory Pattern
Mudasir Qazi
 
PPTX
EJB3 Basics
Emprovise
 
PPTX
Next.js - ReactPlayIO.pptx
DivyanshGupta922023
 
PPTX
ASP.NET Core MVC + Web API with Overview
Shahed Chowdhuri
 
PPTX
Rest presentation
srividhyau
 
PPT
WCF
Vishwa Mohan
 
PPTX
Angular Directives
Malla Reddy University
 
PDF
Angular - Chapter 3 - Components
WebStackAcademy
 
PPT
Asp.net.
Naveen Sihag
 
PDF
GraphQL-ify your APIs
Soham Dasgupta
 
PPTX
Spring 3.x - Spring MVC - Advanced topics
Guy Nir
 
PPTX
Common language runtime clr
SanSan149
 
PPTX
C# Framework class library
Prem Kumar Badri
 
PDF
Learn Entity Framework in a day with Code First, Model First and Database First
Jibran Rasheed Khan
 
Angular - Chapter 1 - Introduction
WebStackAcademy
 
Asp.Net Core MVC , Razor page , Entity Framework Core
mohamed elshafey
 
Angular
Lilia Sfaxi
 
Meetup React Sanca - 29/11/18 - React Testing
Augusto Lazaro
 
Design Patterns - Abstract Factory Pattern
Mudasir Qazi
 
EJB3 Basics
Emprovise
 
Next.js - ReactPlayIO.pptx
DivyanshGupta922023
 
ASP.NET Core MVC + Web API with Overview
Shahed Chowdhuri
 
Rest presentation
srividhyau
 
Angular Directives
Malla Reddy University
 
Angular - Chapter 3 - Components
WebStackAcademy
 
Asp.net.
Naveen Sihag
 
GraphQL-ify your APIs
Soham Dasgupta
 
Spring 3.x - Spring MVC - Advanced topics
Guy Nir
 
Common language runtime clr
SanSan149
 
C# Framework class library
Prem Kumar Badri
 
Learn Entity Framework in a day with Code First, Model First and Database First
Jibran Rasheed Khan
 

Viewers also liked (20)

PPTX
MVC 6 Introduction
Sudhakar Sharma
 
PPTX
Asp.Net MVC Intro
Stefano Paluello
 
PPTX
Dotnet Basics Presentation
Sudhakar Sharma
 
PPTX
MVC - Introduction
Sudhakar Sharma
 
PPTX
ASP.NET Web API and HTTP Fundamentals
Ido Flatow
 
PPTX
Introduction to HTTP/2
Ido Flatow
 
PPTX
Asp.net mvc 5 course module 1 overview
Sergey Seletsky
 
PPTX
Getting Started with ASP.NET MVC
shobokshi
 
PPTX
ASP.NET MVC Best Practices malisa ncube
Malisa Ncube
 
PDF
Webcomponents v2
Dmitry Bakaleinik
 
PPTX
Async patterns in javascript
Ran Wahle
 
PPTX
Responsive ui
Ran Wahle
 
PPTX
Getting started with MVC 5 and Visual Studio 2013
Thomas Robbins
 
PPTX
What's New in WCF 4.5
Ido Flatow
 
PPTX
EF Core (RC2)
Ido Flatow
 
PPTX
The Essentials of Building Cloud-Based Web Apps with Azure
Ido Flatow
 
PPTX
Powershell For Developers
Ido Flatow
 
PPTX
Debugging the Web with Fiddler
Ido Flatow
 
PDF
Getting Started with the TypeScript Language
Gil Fink
 
PPTX
ASP.NET Core 1.0
Ido Flatow
 
MVC 6 Introduction
Sudhakar Sharma
 
Asp.Net MVC Intro
Stefano Paluello
 
Dotnet Basics Presentation
Sudhakar Sharma
 
MVC - Introduction
Sudhakar Sharma
 
ASP.NET Web API and HTTP Fundamentals
Ido Flatow
 
Introduction to HTTP/2
Ido Flatow
 
Asp.net mvc 5 course module 1 overview
Sergey Seletsky
 
Getting Started with ASP.NET MVC
shobokshi
 
ASP.NET MVC Best Practices malisa ncube
Malisa Ncube
 
Webcomponents v2
Dmitry Bakaleinik
 
Async patterns in javascript
Ran Wahle
 
Responsive ui
Ran Wahle
 
Getting started with MVC 5 and Visual Studio 2013
Thomas Robbins
 
What's New in WCF 4.5
Ido Flatow
 
EF Core (RC2)
Ido Flatow
 
The Essentials of Building Cloud-Based Web Apps with Azure
Ido Flatow
 
Powershell For Developers
Ido Flatow
 
Debugging the Web with Fiddler
Ido Flatow
 
Getting Started with the TypeScript Language
Gil Fink
 
ASP.NET Core 1.0
Ido Flatow
 
Ad

Similar to Learning ASP.NET 5 and MVC 6 (20)

PPTX
Introduction to ASP.NET 5
mbaric
 
PPTX
ASP.NET 5
David Voyles
 
PPTX
Get acquainted with the new ASP.Net 5
Suyati Technologies
 
PPTX
Microsoft ASP.NET 5 - The new kid on the block
Christos Matskas
 
PPTX
.Net Core
Bohdan Pashkovskyi
 
PPTX
ASP.NET vNext
Richard Caunt
 
PPTX
Angular on ASP.NET MVC 6
Noam Kfir
 
PPTX
Que hay de nuevo en Visual Studio 2013 y ASP.NET 5.1
Rodolfo Finochietti
 
PPTX
ASP.NET vNext the future of ASP
Clément Hallet
 
PPTX
The next step from Microsoft - Vnext (Srdjan Poznic)
Geekstone
 
PPTX
ASP.NET 5 - Microsoft's Web development platform reimagined
Alex Thissen
 
PPTX
ASP.NET vNext
Alex Thissen
 
PPTX
.NET Core: a new .NET Platform
Alex Thissen
 
PPTX
Short-Training asp.net vNext
Betclic Everest Group Tech Team
 
PPTX
ASP.NET
Chandan Gupta Bhagat
 
PDF
【BS1】What’s new in visual studio 2022 and c# 10
æ—„æœŹăƒžă‚€ă‚Żăƒ­ă‚œăƒ•ăƒˆæ ȘćŒäŒšç€Ÿ
 
PPTX
ASP.NET - Building Web Application..in the right way!
Commit Software Sh.p.k.
 
PPTX
ASP.NET - Building Web Application..in the right way!
Fioriela Bego
 
PPTX
Project K, Vnext and Owin
Hrvoje Hudoletnjak
 
Introduction to ASP.NET 5
mbaric
 
ASP.NET 5
David Voyles
 
Get acquainted with the new ASP.Net 5
Suyati Technologies
 
Microsoft ASP.NET 5 - The new kid on the block
Christos Matskas
 
.Net Core
Bohdan Pashkovskyi
 
ASP.NET vNext
Richard Caunt
 
Angular on ASP.NET MVC 6
Noam Kfir
 
Que hay de nuevo en Visual Studio 2013 y ASP.NET 5.1
Rodolfo Finochietti
 
ASP.NET vNext the future of ASP
Clément Hallet
 
The next step from Microsoft - Vnext (Srdjan Poznic)
Geekstone
 
ASP.NET 5 - Microsoft's Web development platform reimagined
Alex Thissen
 
ASP.NET vNext
Alex Thissen
 
.NET Core: a new .NET Platform
Alex Thissen
 
Short-Training asp.net vNext
Betclic Everest Group Tech Team
 
【BS1】What’s new in visual studio 2022 and c# 10
æ—„æœŹăƒžă‚€ă‚Żăƒ­ă‚œăƒ•ăƒˆæ ȘćŒäŒšç€Ÿ
 
ASP.NET - Building Web Application..in the right way!
Commit Software Sh.p.k.
 
ASP.NET - Building Web Application..in the right way!
Fioriela Bego
 
Project K, Vnext and Owin
Hrvoje Hudoletnjak
 
Ad

More from Ido Flatow (16)

PPTX
Google Cloud IoT Core
Ido Flatow
 
PPTX
Introduction to HTTP/2
Ido Flatow
 
PPTX
Production Debugging War Stories
Ido Flatow
 
PPTX
Introduction to HTTP/2
Ido Flatow
 
PPTX
Production debugging web applications
Ido Flatow
 
PPTX
From VMs to Containers: Introducing Docker Containers for Linux and Windows S...
Ido Flatow
 
PPTX
Building IoT and Big Data Solutions on Azure
Ido Flatow
 
PPTX
Migrating Customers to Microsoft Azure: Lessons Learned From the Field
Ido Flatow
 
PPTX
Debugging your Way through .NET with Visual Studio 2015
Ido Flatow
 
PPTX
Introducing HTTP/2
Ido Flatow
 
PDF
IaaS vs. PaaS: Windows Azure Compute Solutions
Ido Flatow
 
PPTX
Advanced WCF Workshop
Ido Flatow
 
PPTX
IIS for Developers
Ido Flatow
 
PPTX
Debugging with Fiddler
Ido Flatow
 
PPTX
Caching in Windows Azure
Ido Flatow
 
PPTX
Automating Windows Azure
Ido Flatow
 
Google Cloud IoT Core
Ido Flatow
 
Introduction to HTTP/2
Ido Flatow
 
Production Debugging War Stories
Ido Flatow
 
Introduction to HTTP/2
Ido Flatow
 
Production debugging web applications
Ido Flatow
 
From VMs to Containers: Introducing Docker Containers for Linux and Windows S...
Ido Flatow
 
Building IoT and Big Data Solutions on Azure
Ido Flatow
 
Migrating Customers to Microsoft Azure: Lessons Learned From the Field
Ido Flatow
 
Debugging your Way through .NET with Visual Studio 2015
Ido Flatow
 
Introducing HTTP/2
Ido Flatow
 
IaaS vs. PaaS: Windows Azure Compute Solutions
Ido Flatow
 
Advanced WCF Workshop
Ido Flatow
 
IIS for Developers
Ido Flatow
 
Debugging with Fiddler
Ido Flatow
 
Caching in Windows Azure
Ido Flatow
 
Automating Windows Azure
Ido Flatow
 

Recently uploaded (20)

PPTX
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PDF
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
PDF
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
PPTX
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
PPTX
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
PPTX
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
PDF
Executive Business Intelligence Dashboards
vandeslie24
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
Tally software_Introduction_Presentation
AditiBansal54083
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
Executive Business Intelligence Dashboards
vandeslie24
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 

Learning ASP.NET 5 and MVC 6

  • 1. © Copyright SELA Software & Education Labs Ltd. | 14-18 Baruch Hirsch St Bnei Brak, 51202 Israel | www.selagroup.com Ido Flatow Getting to Know ASP.NET 5 and MVC 6
  • 2. Agenda Introduction to ASP.NET 5 What’s new in ASP.NET 5 ASP.NET MVC 6
  • 3. About Me Senior Architect, Sela Group Microsoft Regional Director, and an ASP.NET/IIS MVP Co-author of courses and books Focus on server, web, and cloud Manager of the Israeli Web Developers User Group
  • 4. History of ASP (18 years) 1996 - Active Server Pages (ASP) 2002 – ASP.NET 2008 – ASP.NET MVC 2010 – ASP.NET Web Pages 2012 – ASP.NET Web API, SignalR 2014 – ASP.NET vNext
  • 5. Current ASP.NET stack Windows Server IIS .NET Framework ASP.NET Web Forms MVC Web API System.Web HTTP Modules HTTP Handlers Request Pipeline Caching Session State
  • 6. Problems with ASP.NET architecture Limited hosting possibilities (IIS only) Dependency on IIS environment (System.Web) Web evolves faster than .NET framework Requires full-blown .NET framework - resource intensive and not web-friendly Hard to optimize for lightweight high- performance apps
  • 7. Introducing ASP.NET 5 stack OS .NET CLR ASP.NET Web API MVC Web Pages Host IIS Self-hosted .NET Core CLR Middleware
  • 10. .NET Core & App Models
  • 11. Caution At the time of this presentation, we are using DNX-CLR-x86 1.0.0-beta4 (ASP.NET 5 beta 4) As things are moving really fast in this new world, it’s very likely that the things explained here will slightly change
  • 12. ASP.NET 5 – Agility Faster Development Cycle Features are shipped as packages Framework ships as part of the application More Control Zero day security bugs patched by Microsoft Same code runs in development and production Developer opts into new versions, allowing breaking changes
  • 13. ASP.NET 5 - Fast Runtime Performance Faster startup times Lower memory / higher density (> 90% reduction) Modular, opt into just features needed Use a raw socket, framework or both Development productivity and low friction Edit code and refresh browser Flexibility of dynamic environment with the power of .NET Develop with Visual Studio, third party and cloud editors
  • 14. ASP.NET 5 – Cross Platform Runtime Windows, Mac, Linux Editors Visual Studio, Text, Cloud editors OmniSharp – Sublime, Emacs, Vi, etc. No editors (command line) All Open Source with Contributions
  • 15. ASP.NET 5 Features New flexible and cross-platform runtime New modular HTTP request pipeline Robust environment configuration Unified programming model for MVC API See changes without re-building the project Side-by-side versioning of the .NET Framework Built in Dependency Injection Ability to self-host or host on IIS Open source in GitHub
  • 16. File  New Project  Web Web App Class Lib? Console App?
  • 19. Let's talk about OWIN Open Web Interface for .NET Community project (http://owin.org) Decouples application from server Enforces modularity of the server Stack of modules (middlewares) is processing the request from application to server Microsoft implementation of OWIN is "Katana"
  • 20. OWIN Implementation Host Middleware Server Application Middleware Middleware Request Response Startup, bootstrapping, process management Manages sockets, delegates to middlewares Pass-through components stack Your code
  • 21. ASP.NET 5 Middlewares Improved HTTP performance New HTTP request pipeline that is lean and fast The new pipeline also supports OWIN You choose what to use in your application By registering middlewares public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory) { app.UseErrorHandler("/Home/Error"); app.UseStaticFiles(); app.UseIdentity(); app.UseMvc(routes => ...) }
  • 22. Custom Middleware Create middleware class app.UseMiddleware<AppHeaderMiddleware>(); // Register before app.UseMvc(...); public class AppHeaderMiddleware { private readonly RequestDelegate next; public AppHeaderMiddleware(RequestDelegate next) { this.next = next; } public async Task Invoke(HttpContext context) { context.Response.Headers.Append( "X-Application", "ASP.NET 5 Sample App"); await this.next.Invoke(context); } } Register in Startup.cs (IApplicationBuilder)
  • 24. Package Management ASP.NET 5 introduces a new, lightweight way to manage dependencies in your projects No more assembly references Instead referencing NuGet packages project.json file
  • 25. Structure of the "project.json" file Dependencies - lists all the dependencies of your application (NuGet, source files, etc.) Configuration - compilation settings (debug, release) Frameworks - target frameworks with their dependencies Sources - what should be compiled Web root - server root of the app Shared files - files shared with dependent projects Commands - commands available to “dnx” Scripts - pre/post events to hook scripts to Metadata - general project information
  • 28. Debugging without Roslyn Change the code C# Compiler invoked Load code in memory Execute the dll dll loaded in memory from File system Emits the dll in file system
  • 29. Debugging with Roslyn Change the code Load code in memory Code is Executed in memory Roslyn compiles code in memory Time reduced from 7-8 second to 1-2 second
  • 30. "K“ / ”DNX” Command Line Tools KRE / DNX- Runtime Environment Engine that runs your application (compilation system, SDK tools, and the native CLR hosts) KVM / DNVM - Version Manager Tool for updating and installing different versions of KRE/DNX KPM / DNU- Package Manager Tool to restore and install (NuGet) packages needed by applications to run K / DNX Entry point to the runtime - starts the runtime with commands
  • 31. OpenSource Runtime Loader IIS: WebEngine4 Exe: OS DNX Operating SystemWindows Windows, OSX, Linux Libraries Loose, GAC, Nuget NuGet, NPM, Bower App FrameworksFCL, GAC, NuGet NuGet Web ServerIIS IIS, HTTP.SYS, Kestrel Application HostSystem.Web DNX Platform Libraries.NET BCL & FCL .NET BCL & FCL .NET on Nuget Runtime.NET CLR .NET CLR .NET Core CLR Application MSBuild/CodeDom -> csc.exe DNX (Roslyn) Present vs. Future
  • 32. © Copyright SELA Software & Education Labs Ltd. | 14-18 Baruch Hirsch St Bnei Brak, 51202 Israel | www.selagroup.com MVC 6
  • 34. ASP.NET 5 with MVC 6
  • 35. MVC + Web API + Web Pages = ASP.NET MVC 6!
  • 36. ASP.NET MVC 6 No more duplication - one set of concepts Used for creating both UI and API Smooth transition from Web Pages to MVC Based on the new ASP.NET 5 pipeline Built DI first Runs on IIS or self-host
  • 37. Getting Started with MVC 6 Startup.cs Project.json app.UseMvc(routes => { routes.MapRoute("default", "{controller}/{action}/{id?}", new { controller = "Home", action = "Index" }); }); app.UseServices(services => { services.addMvc(); }) "dependencies": { "Microsoft.AspNet.Server.IIS": "1.0.0-*", // Add this: "Microsoft.AspNet.Mvc": "6.0.0-*" }
  • 38. Routing Template Improvements Inline constraints Product/{ProductId:long} Product/{ProductName:alpha} Product/{ProductName:minlength(10)} Product/{productId:regex(^d{4}$)} Optional parameters Product/{productId:long?} Default values Product/{productId:long=1} Available with MapRoute() and [Route()] https://github.com/aspnet/Routing/tree/dev/src/ Microsoft.AspNet.Routing
  • 39. Where is the Web API Configuration? Route configuration -> attribute-based routing Message handlers -> middleware pipeline Filters and Formatters -> startup.cs app.UseServices(services => { services.Configure<MvcOptions>(options => { options.AddXmlDataContractSerializerFormatter(); options.Filters.Add(new ValidatorFilterAttribute()); }); }
  • 40. Controllers – Two Birds, One Stone API – similar, but different UI – same as with MVC 5 [Route("api/[controller]")] public class ProductsController : Controller { [HttpGet("{id:int}")] public Product GetProduct(int id) { return new Product() { ID = id }; } } public class HomeController : Controller { public IActionResult Index() { return View(); } }
  • 41. Actions – API with IActionResult [HttpGet("{id:int}", Name = "GetByIdRoute")] public IActionResult GetById (int id) { var item = _items.FirstOrDefault(x => x.Id == id); if (item == null) { return HttpNotFound(); } return new ObjectResult(item); } [HttpPost] public IActionResult CreateTodoItem([FromBody] TodoItem item) { _items.Add(item); return CreatedAtRoute( "GetByIdRoute", new { id = item.Id }, item); }
  • 42. IActionResult for UI and API https://github.com/aspnet/Mvc/tree/dev/src/ Microsoft.AspNet.Mvc.Core/ActionResults UI API PartialViewResult BadRequestResult RedirectResult ContentResult ViewResult CreatedAtRouteResult JsonResult HttpStatusCodeResult JsonResult ObjectResult ChallengeResult HttpNotFoundResult FileContentResult
  • 43. Content Negotiation MVC still respects Accept headers The XML formatter was removed from the MVC 6 pipeline You can manually add it to the Formatters collection Forcing a content-type: Return a JsonResult Use the [Produces("application/json")] attribute Additional changes: Actions returning string result in text/plain responses Returning null/void – response will be HTTP 204 (no content)
  • 44. Last Controller Goodie - DI Dependency Injection and MVC ASP.NET 5 is DI-friendly Basic DI container available throughout the stack BYOC is also supported (already implemented for Autofac, Ninject, StructureMap, Unity, and Windsor) Out-of-the-box container supports Singleton / Instance – single instance Transient – new instance each time Scoped – new instance per request https://github.com/aspnet/DependencyInjection/tree /dev/src
  • 45. Last Controller Goodie - DI public class ProductsController : Controller { private readonly IProductsRepository _repository; public ProductsController(IProductsRepository repository) { this._repository = repository; } public IActionResult Index() { var products = _repository.GetAllProducts(); return View(products); } } app.UseServices(services => { services.AddTransient<IProductsRepository, DefaultProductsRepository>(); });
  • 46. Look Ma No Controller Use the Controller suffix Inject HTTP request, principal, and view data with: Convention-based property injection Constructor injection public class SimpleController { [Activate] public ActionContext ActionContext { get; set; } [Activate] public ViewDataDictionary ViewData { get; set; } [Activate] public IUrlHelper Url { get; set; } public string Get() { return "Hello world"; } }
  • 47. Enough with Controllers, What About MVC Views? Oh, right!
  • 48. Child Actions in MVC <6 Rendering partial views with controller logic and model Do not confuse with Html.Partial @Html.Action("GetProductDetails", "Products", new { id = 1}) [ChildActionOnly] public ActionResult GetProductDetails(int id) { var product = _repository.GetProduct(id); return PartialView("ProductDetails", product); }
  • 49. Child Actions in MVC 6 So what’s the problem? Part of a controller, but invoked from a view Controller flow must distinguish between HTTP calls and view calls Pattern lacks an asynchronous invocation Solution? Replace child actions with View Components Same partial views, but declared in a separate class Think of it as a “mini-controller” Supports the same DI and POCO features as a controller Implement actions as synchronous or asynchronous
  • 50. View Components in MVC 6 //[ViewComponent(Name = "ProductDetails")] public class ProductDetailsViewComponent : ViewComponent { private readonly IProductsRepository _repository; public ProductDetailsViewComponent(IProductsRepository repository) { _repository = repository; } public IViewComponentResult Invoke(int id) { var product = _repository.GetProduct(id); return View(product); } @Component.Invoke("ProductDetails", 1) // Or as async, if InvokeAsync is implemented in the view component @await Component.InvokeAsync("ProductDetails", 1)
  • 51. And the Partial View? Create a default.cshtml file (content structured similar as with MVC <6) Place file in: Controller-specific: Views/{controller}/Components/ProductDetails/Default.cshtml Shared: Views/Shared/Components/ProductDetails/Default.cshtml Customizing view name is supported Create a file other than Default.cshtml Return View(viewName, model)
  • 52. Injecting Services to Views Preferable than using static classes/methods Use interfaces instead of concrete types Register in IoC using different lifecycles public class CatalogService : ICatalogService { public async Task<int> GetTotalProducts() {...} // From ICatalogService } @inject MyApp.Services.ICatalogService Catalog <html> <body> <h3>Number of products in the catalog</h3> @await Catalog.GetTotalProducts() </body> </html> services.AddTransient<ICatalogService, CatalogService>();
  • 53. Last, but not Least, Tag Helpers Do this: Ah? What’s that? Instead of doing this: <form asp-anti-forgery="true" asp-action="UpdateProduct"> 
 </form> using (Html.BeginForm("UpdateProduct", "Products", FormMethod.Post)) { @Html.AntiForgeryToken() 
 } It’s the return of Web Controls, NOOOOOO!!!
  • 54. Tag Helpers are not Evil Tag Helpers generate markup only within their enclosing tag Less Razor/HTML mess in the .cshtml file JavaScript directive style approach Use C# to better construct the markup Add/remove parts from the inner content Generate complex HTML (recursive, nested, 
) Cache the output
  • 55. Existing Tag Helpers HTML elements <a>, <form>, <input>, <label>, <link>, <script>, <select>, <textarea> Logical <cache> Placeholders ValidationSummary (<div>), ValidationMessage (<span>) You can create your own Tag Helpers Check out the source for reference https://github.com/aspnet/Mvc/tree/dev/src/Micros oft.AspNet.Mvc.TagHelpers
  • 56. Key Improvements in ASP.NET 5 Totally modular NuGet is first-class citizen in ASP.NET 5 Everything is a package Lightweight - you use minumum set of modules Faster startup, lower memory (>90%) Does not require .NET Framework installation - runtime environment (CLR) can be deployed with your application
  • 57. Key Improvements in ASP.NET 5 Cross platform - can be hosted anywhere: IIS, self-hosted, Linux, MAC... Web Forms are left aside for now Better developer experience No-compile debugging with Roslyn, MVC unified programming model, basic DI out-of-the-box... Everything is open-source Architecture is OWIN based
  • 58. Getting Started with ASP.NET 5 Ships with Visual Studio 2015 Walkthroughs and samples at http://asp.net/vnext Documentation at http://docs.asp.net/en/latest Get the code from http://github.com/aspnet Read blogs at http://blogs.msdn.com/b/webdev Try out a nightly build from MyGet https://www.myget.org/F/aspnetvnext My Info [email protected] @idoFlatow http://bit.ly/flatowblog

Editor's Notes

  • #38: Other dependencies that people may find relevant: aspnet.diagnostics, server.weblistener
  • #42: Don’t use void with beta3, it ignores status codes set in the method