SlideShare a Scribd company logo
.NET Core 2
E i suoi fratelli
Introduzione al nuovo framework di sviluppo fornito da Microsoft
NET CORE
2
Agenda
1
.NET Core 2
1. Visual Basic Support
2. ARM - IoT support
2
ASP .NET Core 2
1. SPA Templates
2. Kestrel Improvements
3. Razor Support for C# 7.1
4. Razor Pages
3
.NET Standard 2
1. 70% compatibilità Nuget
2. Xamarin support
3. WCF
4. SQLite
4
.Entity Framework Core 2
1. Context Pool
2. Like function
3. String interpolations
4. Scalar function mapping
5. Query filter - soft delete
6. Manual compiled queries
3
Presentazione
@ATosato86
andreatosato
andreatosato
ANDREA TOSATO
.NET CORE 2
NET CORE
VB support, ARM support
5
Da .NET Framework a .NET Core
6
Il futuro: .NET Standard
7
Nuovo Glossario
8
Metapackage
9
Solo C#?
Click to edit Master title style
Demo
Visual Basic Support
11
.NET Portability Analyzer
https://github.com/Microsoft/dotnet-apiport/releases
• Analysis of a single project, solution, or binaries
• Analysis against multiple .NET platforms simultaneously
• Generation of multiple analysis reports in different formats. Supported formats are:
• JSON
• HTML
• Excel
• Configurable report options in the Options pane
• View and save generated reports in a tool window
Click to edit Master title style
Demo
NET Portability Analyzer
13
.NET Core – Supported SO
Già disponibile in tutte le Azure Region. ASP .NET Core viene rilasciato tramite Azure Container Registry
6 nuove piattaforme supportate: Debian Stretch, SUSE Linux Enterprise Server 12 SP2, and macOS High
Sierra.
Supportati Versione Architettura
Windows Client 7 SP1+, 8.1 x64, x86
Windows 10 Client Version 1607+ x64, x86
Windows Server 2008 R2 SP1+ x64, x86
Supportati Versione Architettura
Mac OS X 10.12+ x64
Non più supportati Versione Architettura
Fedora 24 x64
Ubuntu 16.10 x64
openSUSE 42.1 x64
14
.NET Core – Supported SO
Supportati Versione Architettura
Red Hat Enterprise Linux
CentOS
Oracle Linux
7 x64
Fedora 25, 26 x64
Debian 9, 8.7+ x64
Ubuntu
Linux Mint
17.04, 16.04, 14.04
18, 17
x64
openSUSE 42.2+ x64
SUSE Enterprise Linux (SLES) 12 SP2+ x64
15
RyuJIT
RyuJIT is the x86 JIT in .NET Core 2.0
Open Source - RyuJIT is open source. JIT32 is not open source.
Single JIT Codebase - There is now a single codebase for the CoreCLR JIT. This helps everyone who is
working on platform expansion and who is investing in JIT improvements.
An example is Samsung, who is investing in Linux x86 with RyuJIT x86.
Performance - RyuJIT generally takes longer to compile than JIT32, but its optimizer can generate faster
code. The performance difference may not be significant
RyuJIT has more features than JIT32 https://github.com/dotnet/announcements/issues/10
16
dotnet restore
I seguenti comandi vanno a richiamare dotnet restore:
• new
• run
• build
• publish
• pack
• test
17
Raspberry
dotnet publish -c Release -r linux-arm
Per eseguire correttamente una applicazione ARM su Raspberry, è necessario installare i prerequisiti del
sistema.
Per Raspberry (Debian STRETCH):
sudo apt-get install curl libunwind8 gettext
18
Raspberry
This library enables developers to use the various Raspberry Pi's hardware
modules
Pi.Camera Provides access to the offical Raspberry Pi Camera module.
Pi.Info Provides information on this Raspberry Pi's CPU and form factor.
Pi.Gpio Provides access to the Raspberry Pi's GPIO as a collection of GPIO Pins.
Pi.Spi Provides access to the 2-channel SPI bus.
Pi.I2c Provides access to the functionality of the i2c bus.
Pi.Timing Provides access to The PI's Timing and threading API.
Per copiare i file sul sistema Rasperry, è molto utile l’applicazione: WinSCP (https://winscp.net/)
Per accedere ai PIN è possibile utilizzare dei progetti come:
https://github.com/unosquare/raspberryio
Sono presenti altri progetti simili.
Microsoft non ha rilasciato nessuno strumento nativo per accedere ai PIN.
Click to edit Master title style
Demo
ARM - IoT support
ASP .NET CORE 2
NET CORE
SPA Templates, Kestrel Improvements
Razor C# 7.1, Razor Pages
Click to edit Master title style
“ ASP.NET Core is a cross-platform,
high-performance, open-source framework for
building modern, cloud-based, Internet-connected
applications
- Microsoft
22
Timeline
ASP .NET Core
1 ASP NET 5
Beta 6
27/7/2015
2 ASP NET 5
Beta 8
21/9/2015
4 Uscita tools in preview
RC2
16/5/2016
5 Nascita di ASP .NET Core
1.0.0
27/6/2016
3
RC1
Nov 2015
7
2.0.0
14/8/2017
6 Tool definitivi
1.1.0
Nov 2016
ASP .NET Core 2.1.0
SignalR
25
ASP .NET 4.6 vs ASP .NET Core
26
Pipeline
Uguale a quella del vecchio framework
27
Meta package
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<MvcRazorCompileOnPublish>true</MvcRazorCompileOnPublish>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
</ItemGroup>
</Project>
Generando un nuovo progetto MVC con la versione 1.0 venivano inseriti ben 94 file, molti dei quali DLL.
Allo stesso modo, con ASP .NET MVC Core 2 da 94 file e con l’utilizzo dei meta package siamo passi a 13 file.
I benefici sono indiscutibili poichè l’ecosistema passa da 22MB a meno di 13MB
28
SPA template
E additional template
Click to edit Master title style
Demo
SPA template
30
Additional template
https://github.com/dotnet/templating
https://github.com/dotnet/templating/wiki/Available-templates-for-dotnet-new
http://dotnetnew.azurewebsites.net/
Per verificare i template installati sulla macchina (dotnet new --list)
ASP.NET Core SPA Templates dotnet new -i "Microsoft.AspNetCore.SpaTemplates::*"
ASP.NET Core Boilerplate dotnet new -i "Boilerplate.Templates::*"
Auth0 Templates dotnet new -i "Auth0.Templates::*"
AWS Lambda .NET Core Templates dotnet new -i "Amazon.Lambda.Templates::*"
Cake.Frosting dotnet new -i "Cake.Frosting.Template::*"
DotVVM dotnet new -i "DotVVM.Templates::*"
IdentityServer4.Templates dotnet new -i "identityserver4.templates::*"
Kentico Cloud Boilerplate dotnet new -i "KenticoCloud.CloudBoilerplateNet::*"
Mono Game dotnet new -i "MonoGame.Template.NETCore::*"
MSBuild extension dotnet new -i "MSBuildExtensionTemplate::*"
31
Additional template
NancyFX Template not on nuget.org
NSpec Templates dotnet new -i "dotnet-new-nspec::*"
NUnit 3 Test Project Template dotnet new -i "NUnit3.DotNetNew.Template::*"
Pioneer Console Boilerplate - Boilerplated .NET Core
console application that includes dependency injection,
logging and configuration.
dotnet new -i "Pioneer.Console.Boilerplate::*"
PowerShell Core dotnet new -i "FiftyProtons.Templates.PSCore::*"
Prism Forms QuickStarts - Empty & QuickStart project
Templates for Prism for Xamarin Forms. Requires dotnet
cli 2.0 pre3+
dotnet new -i "Prism.Forms.QuickstartTemplates::*"
Raspberry Pi 3 - C# template for .NET Core 2 IoT
applications.
dotnet new -i "RaspberryPi.Template::*"
ServiceStack dotnet new -i "ServiceStack.Core.Templates::*"
Template templates - Templates to create new project
and item templates. Requires new3.
dotnet new -i "FiftyProtons.Templates.DotNetNew::*"
32
In applicazioni ASP .NET
Classiche, tutto viene
ospitato in IIS Worker
Process (w3wp.exe)
IIS WebServer in vecchie applicazioni
33
Le applicazioni vengono eseguite
in un processo console separato
in cui viene eseguito il
WebServer Kestrel.
Questa infrastruttura ha
pesantemente modificato le
performance.
Kestrel in ASP .NET Core
34
Kestrel in ASP .NET Core 2
Se l'applicazione accetta richieste solo da una rete interna, è possibile utilizzare Kestrel da solo.
Se esegui la tua applicazione su Internet, devi utilizzare IIS, Nginx o Apache come reverse server proxy.
Un server reverse proxy riceve le richieste HTTP da Internet e le trasmette a Kestrel dopo alcune
manipolazioni preliminari.
Uno scenario che richiede un reverse proxy è quando si dispone di più applicazioni che condividono lo stesso
IP e la porta in esecuzione su un singolo server. Questo non funziona direttamente con Kestrel perché non
supporta la condivisione dello stesso IP e della porta tra più processi. Kestrel gestisce tutto il traffico per
quella porta indipendentemente dall'intestazione host
35
HttpSys in ASP .NET Core 2 (ex WebListener)
HttpSys è una alternativa a Kestrel per le sole macchine Windows ed è possibile esporre l’applicazione ad
internet. Può essere usata anche per applicazioni intranet. Non può essere utilizzato con IIS e IIS express.
Non richiede un reverse proxy. HttpSys è una buona
soluzione per applicazioni intranet che richiedono
scenari non supportati da Kestrel, quali: Windows
authentication
HttpSys supports the following features:
• Windows Authentication
• Port sharing
• HTTPS with SNI
• HTTP/2 over TLS (Windows 10)
• Direct file transmission
• Response caching
• WebSockets (Windows 8)
Supported Windows versions:
Windows 7 and Windows Server 2008 R2
and later
36
Kestrel improvement
Miglioramenti sulle performance.
In aggiunta sono state implementate nuove funzionalità come i limits.
• Maximum Client Connections
• Maximum Request Body Size
• Maximum Request Body Data Rate
Limitare il server Kestrel significa servire in maniera efficace i soli client che possono ricevere una risposta in tempi veloci.
“Strozzare” sul nascere le connessioni dei client che non si riesce a servire, garantisce maggior efficacia per il webserver
https://github.com/aspnet/KestrelHttpServer/blob/dev/src/Kestrel.Core/KestrelServerLimits.cs
.UseKestrel(options =>
{
options.Limits.MaxConcurrentConnections = 100;
options.Limits.MaxConcurrentUpgradedConnections = 100;
});
37
Kestrel improvement
Plain text
Plain Text
Intended to highlight the HTTP
efficiency of the server & stack.
Implementations are free to
cache the response body
aggressively and
remove/disable components
that aren't required in order to
maximize performance.
38
Kestrel improvement
Plain Text with HTTP Pipelining
39
Kestrel improvement
Plain Text with HTTP Pipelining
https://blogs.msdn.microsoft.com/dotnet/2017/06/07/performance-improvements-in-net-core/
https://github.com/aspnet/benchmarks
Like the Plain Text
scenario above but with
HTTP pipelining enabled
at a depth of 16. Only
stacks/servers that show
an improvement with
pipelining are included.
40
Kestrel nuova configurazione
Nuova configurazione allo startup
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
41
Performance ASP .NET Core
Gli assembly che fanno parte di ASP.NET Core sono stati pre-JITted, ovvero
sono già pronti in linguaggio macchina per essere immediatamente eseguiti.
Come conseguenza di ciò, l'applicazione ora si avvia in meno tempo ed il
framework riesce a processare una quantità maggiore di richieste al secondo.
42
Razor
Razor view pre-compilation is
enabled during publish by default,
reducing the publish output size
and application startup time.
43
Migliorati il supporto ad HTTP
Ora è possibile interpretare e utilizzare ETag
o LastModified date sui contenuti trasmessi
var data = Encoding.UTF8.GetBytes(“Sample text from a binary array");
var entityTag = new EntityTagHeaderValue(""MyEtagValue"");
return File(data, "text/plain", "downloadName.txt",
lastModified: DateTime.UtcNow.AddSeconds(-5),
entityTag: entityTag);
44
Razor e C# 7.1
Razor si adegua alla sistassi C# 7.1
Per abilitare la nuova sintassi C# è necessario modificare il .CSPROJ con il tag:
<LangVersion>latest</LangVersion>
Click to edit Master title style
Demo
C# 7.1
46
Razor e C# 7.1
Default Literal Expressions
int i = default(int); // Current
int i = default; // New
var i = default; // Error: no target type
const string S = null;
const string S = default;
const int? NI = null; // error
const int? NI = default; // error
47
Razor e C# 7.1
Default Literal Expressions
void M(MyStruct ms = default) { ... }
bool b = null is T; // allowed, always false
if (0 is int) { ... } // True: 0 is an int
if (default(int) is int) { ... } // True: 0 is still an int
if (default is int) { ... } // Would be false! default(object) is null, which is not an int.
Func<string, bool> whereClause = default(Func<string, bool>);
Si può omettere l’operatore di destra
Func<string, bool> whereClause = default;
48
Razor e C# 7.1
Infer tuple names
Action y = () => M();
var t = (x: x, y);
t.y(); // this might have previously picked up an extension method called “y”, but would now call the lambda.
Tuple Design:
https://github.com/dotnet/roslyn/blob/master/docs/features/tuples.md
int count = 5;
string label = "Colors used in the map";
var pair = (count, label); // element names are "count" and "label"
49
C# 7.1
Async Main
public static void Main()
{
MainAsync().GetAwaiter().GetResult();
}
private static async Task MainAsync()
{
... // Main body here
}
50
C# 7.1
Pattern Matching With Generics
public double Area<T>(T shape) where T : Shape
{
double calculatedArea = 0.0d;
switch (shape)
{
case Circle circle:
calculatedArea = circle.Area();
break;
case Sphere sphere:
calculatedArea = sphere.Area();
break;
}
return calculatedArea;
}
public abstract class Shape
{
public double Radius { get; set; }
public abstract double Area();
}
public class Circle : Shape
{
public override double Area()
{
return Math.PI * Math.Pow(Radius, 2);
}
}
public class Sphere : Shape
{
public override double Area()
{
return 4 * Math.PI * Math.Pow(Radius, 2);
}
}
51
Razor Pages
Ciascuna Razor Page è un'unità autonoma della nostra applicazione web e la si riconosce dalle seguenti caratteristiche:
• Contiene una direttiva @page in cima al file. Questo serve a designarla come una Razor Page e a configurare il routing
affinché sia direttamente invocabile via URL. Una Razor Page situata in /Pages/Products.cshtml sarà raggiungibile dall'URL
/Products;
• Può contenere un blocco @functions all'interno del qual definiremo il code behind della pagina, ovvero proprietà e
metodi che potranno essere richiamati dalla Razor Page. Come in ASP.NET WebForms, il code behind può anche essere
posto in un file di codice separato che ha estensione .cshtml.cs. In questo caso, il file di codice dovrà contenere una classe
che deriva da PageModel;
• I tag helper <form> si arricchiscono degli attributi asp-page e asp-page-handler che permettono di indicare il nome
della pagina che riceverà i dati del form e della function definita in essa;
• Definendo metodi dai nomi speciali come OnGet, OnGetAsync, OnPost o OnPostAsync potremo eseguire del codice
quando la pagina viene richiamata con i metodi HTTP GET o POST. Tali metodi sono equivalenti ad action di ASP.NET
MVC decorate con gli attributi HttpGet o HttpPost;
• Può contenere direttive @inject che usiamo per ottenere istanze di servizi grazie al meccanismo di dependency injection
di ASP.NET Core.
52
Razor Pages
53
Razor Pages – Elementi distintivi
Parametri
@page "{id:int}"
public async Task<IActionResult> OnGetAsync(int id)
{
…
}
https://docs.microsoft.com/en-us/aspnet/core/mvc/razor-pages/
Proprietà del modello
[BindProperty]
public int PageDataID { get; set; }
[BindProperty]
public string Title { get; set; }Tipi di ritorno
return Page();
return RedirectToPage("/");
54
Razor Pages
Metodi personalizzati
Click to edit Master title style
Demo
Razor Pages e Blog template
56
WebAssembly
MONO Project
We have been experimenting with a couple of approaches to bring Mono to the web using WebAssembly - a
technology that can efficiently and safely execute code in web browsers without being limited to Javascript.
Running code written in C or C++ inside the browser has been a big motivator, but most major programming
languages have plans to target WebAssembly as a platform.
WebAssembly has been out for a few months on desktop computers and Android, and with the introduction of iOS
11 it will become nearly universal.
Miguel de Icaza
http://www.mono-project.com/news/2017/08/09/hello-webassembly/
57
WebAssembly
Blazor
An experimental web UI framework using C#/Razor and HTML, running client-side via WebAssembly
The arrival of WebAssembly creates the possibility of building client-side web applications using languages and
runtimes that are more typically used for native app development. Blazor runs .NET code in the browser via a
small, portable .NET runtime called DotNetAnywhere (DNA) compiled to WebAssembly.
The programming model will be familiar to anyone who's worked with Razor (the C#/HTML page format used by
ASP.NET MVC and ASP.NET Pages).
https://github.com/SteveSanderson/Blazor
.NET Standard 2
NET CORE
WCF, Nuget Package, Xamarin support
59
Il futuro: .NET Standard
60
.NET Standard 2.0
Nuove funzionalità
Bigger API Surface: We have more than doubled the set of available APIs from 13k in .NET Standard 1.6
to 32k in .NET Standard 2.0. Most of the added APIs are .NET Framework APIs. These additions make it
much easier to port existing code to .NET Standard, and, by extension, to any .NET implementation of .NET
Standard, such as .NET Core 2.0 and the upcoming version of UWP.
.NET Framework compatibility mode: The vast majority of NuGet packages are currently still targeting
.NET Framework. Many projects are currently blocked from moving to .NET Standard because not all their
dependencies are targeting .NET Standard yet. That's why we added a compatibility mode that allows .NET
Standard projects to depend on .NET Framework libraries as if they were compiled for .NET Standard. Of
course, this may not work in all cases (for instance, if the .NET Framework binaries uses WPF), but we found
that 70% of all NuGet packages on nuget.org are API compatible with .NET Standard 2.0, so in practice it
unblocks many projects.
Broad platform support. .NET Standard 2.0 is supported on the following platforms:
• .NET Framework 4.6.1
• .NET Core 2.0
• Mono 5.4
• Xamarin.iOS 10.14
• Xamarin.Mac 3.8
• Xamarin.Android 7.5
• UWP is work in progress and will ship later this year.
61
Nuget
"We are happy to announce an update to the NuGet client that comes bundled with Visual Studio 2017
version 15.3 RTW and .NET Core 2.0 SDK,“
NuGet said : "This release introduces support for new scenarios such as .NET Core 2.0/.NET Standard
2.0, some new features, a series of bug fixes and performance improvements."
Microsoft earlier pointed out that a May investigation found some 70 percent of NuGet packages (which
manages more than 87,000 unique packages and more than 960,000 package versions) were compatible
with .NET Standard 2.0.
The vast majority of NuGet packages are currently still targeting .NET Framework. Many projects are
currently blocked from moving to .NET Standard because not all their dependencies are targeting .NET
Standard yet. That's why we added a compatibility mode that allows .NET Standard projects to depend on
.NET Framework libraries as if they were compiled for .NET Standard.
NuGet 4.0+ uses at least two global package locations:
User-specific: %userprofile%.nugetpackages
Machine-wide: %ProgramFiles(x86)%Microsoft SDKsNuGetPackages
62
Nuget
Nuovo portale
63
.NET Standard
64
.NET Standard 2.0
Nuove funzionalità
65
How does .NET Standard work?
.NET Standard is represented by
• The NuGet package NetStandard.Library which contains
• The reference assembly netstandard.dll
At build time
• .NET Standard bridges references to existing .NET
Framework and PCL assemblies via type forwarding
At runtime
• Each platform provides an implementation for
netstandard.dll that type forwards to its implementation
66
Type Forwarding?
Type forwarding allows you to move a type to
another assembly without having to
recompile applications that use the original
assembly.
https://docs.microsoft.com/en-us/dotnet/framework/app-domains/type-forwarding-in-the-
common-language-runtime
https://www.youtube.com/watch?v=vg6nR7hS2lI
Click to edit Master title styleWhat can you reference from .NET Standard?
My Standard Library 2.x
.NET Standard Library .NET Framework LibraryPortable Class Library
.NET FRAMEWORK .NET CORE XAMARIN
Via Portability
Via Compatibility Shim
Legend
Application Type
Is able to reference
Click to edit Master title style.NET Standard under the hood - BUILD
TYPE
FORWARDING
netstandard!Object
mscorlib!Object
This happens when you build a .NET Standard-based Library
Click to edit Master title style.NET Standard under the hood - LOAD
TYPE
FORWARDING
This happens when you load .NET Standard-based library
Click to edit Master title style
Demo
SharpZipLib
71
WCF
Client Proxy
System.ServiceModel.Duplex 4.4.0
WCF
.NET Core
System.ServiceModel.Http 4.4.0
System.ServiceModel.NetTcp 4.4.0
System.ServiceModel.Primitives 4.4.0
System.ServiceModel.Security 4.4.0
WCF
Connected Service Provider
E’ possibile referenziare un servizio WCF.
Non è possibile creare un nuovo progetto di tipo WCF.
Risulta necessario avere un progetto .NET Standard > 2.0
La possibilità di utilizzare e referenziare progetti di tipo WCF è
possibile grazione al WCF Connected Service Provider che ci
consente di generare i proxy per le classi del WCF
https://marketplace.visualstudio.com/items?itemName=WCFCORETEAM.VisualStudioWCFConnectedService
Click to edit Master title style
Demo
WCF Service Reference
73
Microsoft.Data.SQLite
Microsoft.Data.Sqlite provides SQLite implementations of the
System.Data.Common interfaces. It is designed to work with the native, C library
"sqlite3" on all platforms where .NET Core and .NET Framework are supported,
including Windows, Linux, macOS, and others.
The good thing about this library is, it’s build for .NET Core, meaning you can
develop and run applications on Windows and non-Windows platform (Mac,
Linux) supporting .NET Core Runtime.
74
NetStandard Roadmap
75
Xamarin Roadmap
2.4 Xamarin.Forms for macOS Preview
vNext (est. Q4 2017)
Xamarin.Forms for GTK# Preview
Deprecation of WP8.0 and 8.1
vNext2 (est. Q1 2018)
Xamarin.Forms for GTK#
Xamarin.Forms for macOS
https://forums.xamarin.com/discussion/85747/xamarin-forms-feature-roadmap/p1
Entity Framework
Core 2
NET CORE
Context Pool, View, Like function
String interpolations,
Scalar function mapping,
Query filter - soft delete,
Manual compiled queries
77
Storia
78
EF Core
• It would work on all operating systems (Linux, Mac) and platforms (Windows Phone, Windows
Store) supported by .NET Core
• Non-relational databases would also be supported, making it not just an ORM: Azure Table
Storage and Redis were the first to be announced
• Fully extensible and provider-based
• A simplified API that is close to the previous one
• New features: shadow properties, ability to mix SQL with LINQ, transparent client-side function
evaluation, high-low identifier generation, batching of queries, improved SQL generation
Support for providers other than SQL Server (SQL Server Compact Edition, SQLite, InMemory,
PostgreSQL,
MySQL, DB2, MyCat, Oracle)
79
Table splitting
It is now possible to map two or more entity types to the same table where the primary key column(s) will be shared and
each row will correspond to two or more entities.
modelBuilder.Entity<Product>()
.HasOne(e => e.Details)
.WithOne(e => e.Product)
.HasForeignKey<ProductDetails>(e => e.Id);
modelBuilder.Entity<Product>().ToTable("Products");
modelBuilder.Entity<ProductDetails>().ToTable("Products");
80
Owned types
An owned entity type can share the same CLR type with another owned entity type, but since it cannot be identified just
by the CLR type there must be a navigation to it from another entity type. The entity containing the defining navigation
is the owner. When querying the owner the owned types will be included by default.
public class Order
{
public int Id { get; set; }
public OrderDetails OrderDetails { get; set; }
}
public class OrderDetails
{
public StreetAddress BillingAddress { get; set; }
public StreetAddress ShippingAddress { get; set; }
}
modelBuilder.Entity<Order>().OwnsOne(p => p.OrderDetails, cb =>
{
cb.OwnsOne(c => c.BillingAddress);
cb.OwnsOne(c => c.ShippingAddress);
});
public class StreetAddress
{
public string Street { get; set; }
public string City { get; set; }
}
81
Model-level query filters
This feature allows LINQ query predicates (a boolean expression typically passed to the LINQ Where query operator) to
be defined directly on Entity Types in the metadata model (usually in OnModelCreating). Such filters are automatically
applied to any LINQ queries involving those Entity Types, including Entity Types referenced indirectly, such as through
the use of Include or direct navigation property references. Some common applications of this feature are:
1. Soft delete - An Entity Types defines an IsDeleted property.
2. Multi-tenancy - An Entity Type defines a TenantId property.
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public int TenantId {get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Post>().HasQueryFilter(
p => !p.IsDeleted
&& p.TenantId == this.TenantId );
}
}
Limitations
Navigation references are not allowed.
This feature may be added based on
feedback.
Filters can only be defined on the root
Entity Type of a hierarchy.
82
Scalar function mapping
Once a method has been registered you can use it anywhere in your queries.
1. By convention the name of the method is used as the name of a function (in this case a user defined function)
when generating the SQL, but you can override the name and schema during method registration
2. Currently only scalar functions are supported
3. You must create the mapped function in the database, e.g. EF Core migrations will not take care of creating it
public class BloggingContext : DbContext
{
[DbFunction]
public static int PostReadCount(int blogId)
{
throw new Exception();
}
}
var query =
from p in context.Posts
where BloggingContext.PostReadCount(p.Id) > 5
select p;
83
Self-contained type configuration for code first
In EF6 it was possible to encapsulate the code first configuration of a specific entity type by deriving from
EntityTypeConfiguraiton. In EF Core 2.0 we are bringing this pattern back:
class CustomerConfiguration : IEntityTypeConfiguration<Customer>
{
public void Configure(EntityTypeBuilder<Customer> builder)
{
builder.HasKey(c => c.AlternateKey);
builder.Property(c => c.Name).HasMaxLength(200);
}
}
...
// OnModelCreating
builder.ApplyConfiguration(new CustomerConfiguration());
84
85
DbContext pooling
If this method is used, at the time a DbContext instance is requested by a controller we will first check if there is an
instance available in the pool. Once the request processing finalizes, any state on the instance is reset and the instance is
itself returned to the pool.
This is conceptually similar to how connection pooling operates in ADO.NET providers and has the advantage of saving
some of the cost of initialization of DbContext instance.
services.AddDbContextPool<BloggingContext>(options =>
options.UseSqlServer(connectionString));
Avoid using DbContext Pooling if you maintain your own state (e.g. private fields) in your derived DbContext class that
should not be shared across requests. EF Core will only reset the state that is aware of before adding a DbContext
instance to the pool.
86
Explicitly compiled queries
Although in general EF Core can automatically compile and cache queries based on a hashed representation of the
query expressions, this mechanism can be used to obtain a small performance gain by bypassing the computation of the
hash and the cache lookup, allowing the application to use an already compiled query through the invocation of a
delegate.
// Create an explicitly compiled query
private static Func<CustomerContext, int, Customer> _customerById =
EF.CompileQuery((CustomerContext db, int id) =>
db.Customers
.Include(c => c.Address)
.Single(c => c.Id == id));
// Use the compiled query by invoking it
using (var db = new CustomerContext())
{
var customer = _customerById(db, 147);
}
87
String interpolation
C# 6 introduced String Interpolation, a feature that allows C# expressions to be directly embedded in string literals,
providing a nice way of building strings at runtime. In EF Core 2.0 we added special support for interpolated strings to
our two primary APIs that accept raw SQL strings: FromSql and ExecuteSqlCommand. This new support allows C# string
interpolation to be used in a 'safe' manner. in a way that protects against common SQL injection mistakes that can
occur when dynamically constructing SQL at runtime.
var city = "London";
var contactTitle = "Sales Representative";
using (var context = CreateContext())
{
context.Set<Customer>()
.FromSql($@"
SELECT *
FROM ""Customers""
WHERE ""City"" = {city} AND
""ContactTitle"" = {contactTitle}")
.ToArray();
}
@p0='London' (Size = 4000)
@p1='Sales Representative' (Size = 4000)
SELECT *
FROM ""Customers""
WHERE ""City"" = @p0
AND ""ContactTitle"" = @p1
88
EF.Functions.Like()
We have added the EF.Functions property which can be used by EF Core or providers to define methods that map to
database functions or operators so that those can be invoked in LINQ queries.
Note that Like() comes with an in-memory implementation, which can be handy when working against an in-
memory database or when evaluation of the predicate needs to occur con the client side.
var aCustomers = from c in context.Customers
where EF.Functions.Like(c.Name, "a%");
select c;
@p0='London' (Size = 4000)
@p1='Sales Representative' (Size = 4000)
SELECT *
FROM ""Customers""
WHERE ""City"" = @p0
AND ""ContactTitle"" = @p1
89
EF Core Power Tools
Reverse Engineer - Generate POCO classes, derived DbContext and mapping for an existing database.
EF Core allows you to use the Scaffold-DbContext or the dotnet ef dbcontext scaffold commands to
reverse engineer a database and create entity and DbContext classes for your database tables.
https://github.com/ErikEJ/SqlCeToolbox/wiki/EF-Core-Power-Tools
(Erik Ejlskov Jensen) ErikEJ
90
EF Core Power Tools
91
Roadmap EF Core 2.1
EntityFrameworkCore 2.1.0
Group By
92
Cosa manca?
• View
• Lazy loading
• many-to-many collections and no inheritance strategies, only single table inheritance
• database initializers and the capability to seed the database
• No interception capabilities
• Stored procedures for Create-Update-Delete (CUD) operations is also not yet implemented. It is possible
to use stored procedures for querying
• It is not possible yet to plug our own custom conventions
• Spatial types
• not possible to reverse-engineer (official)
EF Core is not ready for enterprise-level usage
Dapper ServiceStack.OrmLite
93
Awesome .NET Core
https://github.com/thangchung/awesome-dotnet-core
Frameworks, Libraries and Tools
94
Nov
15
Marco Zamana: Visual Studio Team Service
Andrea Tosato: Azure Functions
95
Grazie
Domande?
CloudGen @CloudGen_Verona CloudGen

More Related Content

PDF
Pottnet MeetUp Essen - ASP.Net Core
PPT
IstioD - From Microservices to Monolithic
PPTX
Open stack icehouse microsoftupdate
PDF
Kubernetes laravel and kubernetes
PPTX
Introduction to the Container Network Interface (CNI)
PPTX
Service mesh from linkerd to conduit (cloud native taiwan meetup)
PDF
Profile your Java apps in production on Red Hat OpenShift with Cryostat | Dev...
PPTX
LlinuxKit security, Security Scanning and Notary
Pottnet MeetUp Essen - ASP.Net Core
IstioD - From Microservices to Monolithic
Open stack icehouse microsoftupdate
Kubernetes laravel and kubernetes
Introduction to the Container Network Interface (CNI)
Service mesh from linkerd to conduit (cloud native taiwan meetup)
Profile your Java apps in production on Red Hat OpenShift with Cryostat | Dev...
LlinuxKit security, Security Scanning and Notary

What's hot (20)

PDF
Red Hat Forum Benelux 2015
PDF
Integrating Linux Systems with Active Directory Using Open Source Tools
PDF
KVM_security
PDF
Leveraging CI/CD to improve open stack operation
PDF
カエルと実践するコンテナ
PPTX
[OpenStack 하반기 스터디] Interoperability with ML2: LinuxBridge, OVS and SDN
PDF
Elasticsearch Monitoring in Openshift
PPT
Introdot Netc Sharp En
PDF
Deploying vn fs with kubernetes pods and vms
PDF
JDO 2019: What you should be aware of before setting up kubernetes on premise...
PDF
OSDC 2018 | Hardware-level data-center monitoring with Prometheus by Conrad H...
PDF
What's new in python 3.8? | Python 3.8 New Features | Edureka
PDF
Elk for applications on k8s
PDF
Securing the Software Supply Chain with TUF and Docker - Justin Cappos and Sa...
PDF
O'Reilly Software Architecture Conference London 2017: Building Resilient Mic...
PDF
OpenShift 4 installation
PDF
Cloud networking deep dive
ODP
OpenShift Origin Internals
ODP
OpenShift Enterprise
PDF
OSDC 2018 | Highly Available Cloud Foundry on Kubernetes by Cornelius Schumacher
Red Hat Forum Benelux 2015
Integrating Linux Systems with Active Directory Using Open Source Tools
KVM_security
Leveraging CI/CD to improve open stack operation
カエルと実践するコンテナ
[OpenStack 하반기 스터디] Interoperability with ML2: LinuxBridge, OVS and SDN
Elasticsearch Monitoring in Openshift
Introdot Netc Sharp En
Deploying vn fs with kubernetes pods and vms
JDO 2019: What you should be aware of before setting up kubernetes on premise...
OSDC 2018 | Hardware-level data-center monitoring with Prometheus by Conrad H...
What's new in python 3.8? | Python 3.8 New Features | Edureka
Elk for applications on k8s
Securing the Software Supply Chain with TUF and Docker - Justin Cappos and Sa...
O'Reilly Software Architecture Conference London 2017: Building Resilient Mic...
OpenShift 4 installation
Cloud networking deep dive
OpenShift Origin Internals
OpenShift Enterprise
OSDC 2018 | Highly Available Cloud Foundry on Kubernetes by Cornelius Schumacher
Ad

Similar to NET core 2 e i fratelli (20)

PPTX
MiM asp.net core
PDF
Introduction to ASP.NET Core
PDF
ASP.NET vs ASP.NET Core
PPTX
ASP.NET Core: The best of the new bits
PPTX
Intro to.net core 20170111
PPTX
.Net: Introduction, trends and future
PPTX
.Net Core - not your daddy's dotnet
PDF
Pottnet Meetup Essen - ASP.Net Core
PPTX
What should you know about Net Core?
PPTX
Dot Net Core 3 with Raspberry Pi
PDF
.NET Core on Mac
PPTX
Dot NET Core 3 with the Raspberry Pi - Virtual Azure Community Day
PPTX
.NET Core Today and Tomorrow
PPTX
Dot Net Core 3 with Raspberry Pi - HackSoc Notts
PPTX
.NET MeetUp Prague 2017 - .NET Standard -- Karel Zikmund
PPTX
Moving forward with ASP.NET Core
PPTX
.NET & C# Updates Fall 2019
PDF
Asp.Net Core MVC , Razor page , Entity Framework Core
PPTX
Steeltoe and the Open Source .NET Renaissance
MiM asp.net core
Introduction to ASP.NET Core
ASP.NET vs ASP.NET Core
ASP.NET Core: The best of the new bits
Intro to.net core 20170111
.Net: Introduction, trends and future
.Net Core - not your daddy's dotnet
Pottnet Meetup Essen - ASP.Net Core
What should you know about Net Core?
Dot Net Core 3 with Raspberry Pi
.NET Core on Mac
Dot NET Core 3 with the Raspberry Pi - Virtual Azure Community Day
.NET Core Today and Tomorrow
Dot Net Core 3 with Raspberry Pi - HackSoc Notts
.NET MeetUp Prague 2017 - .NET Standard -- Karel Zikmund
Moving forward with ASP.NET Core
.NET & C# Updates Fall 2019
Asp.Net Core MVC , Razor page , Entity Framework Core
Steeltoe and the Open Source .NET Renaissance
Ad

More from Andrea Tosato (20)

PPTX
Codemotion Azure Container Apps
PPTX
Lite db for dummies
PDF
Azure Static Web Apps & Blazor
PPTX
Dapr logicapps
PPTX
How to develop modern web application, with no money and nod javascript
PPTX
Entity framework core v3 from sql to no sql
PDF
How to develop modern web application - With no money and no Javascript
PDF
Mixing Identity server, AAD, ASP .NET Identity
PDF
An introduction to GraphQL in .NET Core
PDF
DevOps Heroes 2019
PPTX
dotNetConf2019
PPTX
Cost Optimization - Global Azure Bootcamp 2019
PPTX
Deep Dive Azure Functions - Global Azure Bootcamp 2019
PPTX
Azure Function Workflow
PPTX
Azure Cognitive Service on Container
PPTX
Deploy multi-environment application with Azure DevOps
PPTX
Azure Cognitive Service in Container
PPTX
Azure Signalr Service
PPTX
Xamarin - Microcharts
PPTX
Introduzione Xamarin
Codemotion Azure Container Apps
Lite db for dummies
Azure Static Web Apps & Blazor
Dapr logicapps
How to develop modern web application, with no money and nod javascript
Entity framework core v3 from sql to no sql
How to develop modern web application - With no money and no Javascript
Mixing Identity server, AAD, ASP .NET Identity
An introduction to GraphQL in .NET Core
DevOps Heroes 2019
dotNetConf2019
Cost Optimization - Global Azure Bootcamp 2019
Deep Dive Azure Functions - Global Azure Bootcamp 2019
Azure Function Workflow
Azure Cognitive Service on Container
Deploy multi-environment application with Azure DevOps
Azure Cognitive Service in Container
Azure Signalr Service
Xamarin - Microcharts
Introduzione Xamarin

Recently uploaded (20)

PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Getting Started with Data Integration: FME Form 101
PDF
Mushroom cultivation and it's methods.pdf
PPTX
TLE Review Electricity (Electricity).pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
A Presentation on Touch Screen Technology
PPTX
cloud_computing_Infrastucture_as_cloud_p
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Hindi spoken digit analysis for native and non-native speakers
PPTX
Programs and apps: productivity, graphics, security and other tools
NewMind AI Weekly Chronicles - August'25-Week II
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
Assigned Numbers - 2025 - Bluetooth® Document
MIND Revenue Release Quarter 2 2025 Press Release
Digital-Transformation-Roadmap-for-Companies.pptx
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
Group 1 Presentation -Planning and Decision Making .pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Unlocking AI with Model Context Protocol (MCP)
Getting Started with Data Integration: FME Form 101
Mushroom cultivation and it's methods.pdf
TLE Review Electricity (Electricity).pptx
Encapsulation_ Review paper, used for researhc scholars
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
A Presentation on Touch Screen Technology
cloud_computing_Infrastucture_as_cloud_p
Building Integrated photovoltaic BIPV_UPV.pdf
Hindi spoken digit analysis for native and non-native speakers
Programs and apps: productivity, graphics, security and other tools

NET core 2 e i fratelli

  • 1. .NET Core 2 E i suoi fratelli Introduzione al nuovo framework di sviluppo fornito da Microsoft NET CORE
  • 2. 2 Agenda 1 .NET Core 2 1. Visual Basic Support 2. ARM - IoT support 2 ASP .NET Core 2 1. SPA Templates 2. Kestrel Improvements 3. Razor Support for C# 7.1 4. Razor Pages 3 .NET Standard 2 1. 70% compatibilità Nuget 2. Xamarin support 3. WCF 4. SQLite 4 .Entity Framework Core 2 1. Context Pool 2. Like function 3. String interpolations 4. Scalar function mapping 5. Query filter - soft delete 6. Manual compiled queries
  • 4. .NET CORE 2 NET CORE VB support, ARM support
  • 5. 5 Da .NET Framework a .NET Core
  • 6. 6 Il futuro: .NET Standard
  • 10. Click to edit Master title style Demo Visual Basic Support
  • 11. 11 .NET Portability Analyzer https://github.com/Microsoft/dotnet-apiport/releases • Analysis of a single project, solution, or binaries • Analysis against multiple .NET platforms simultaneously • Generation of multiple analysis reports in different formats. Supported formats are: • JSON • HTML • Excel • Configurable report options in the Options pane • View and save generated reports in a tool window
  • 12. Click to edit Master title style Demo NET Portability Analyzer
  • 13. 13 .NET Core – Supported SO Già disponibile in tutte le Azure Region. ASP .NET Core viene rilasciato tramite Azure Container Registry 6 nuove piattaforme supportate: Debian Stretch, SUSE Linux Enterprise Server 12 SP2, and macOS High Sierra. Supportati Versione Architettura Windows Client 7 SP1+, 8.1 x64, x86 Windows 10 Client Version 1607+ x64, x86 Windows Server 2008 R2 SP1+ x64, x86 Supportati Versione Architettura Mac OS X 10.12+ x64 Non più supportati Versione Architettura Fedora 24 x64 Ubuntu 16.10 x64 openSUSE 42.1 x64
  • 14. 14 .NET Core – Supported SO Supportati Versione Architettura Red Hat Enterprise Linux CentOS Oracle Linux 7 x64 Fedora 25, 26 x64 Debian 9, 8.7+ x64 Ubuntu Linux Mint 17.04, 16.04, 14.04 18, 17 x64 openSUSE 42.2+ x64 SUSE Enterprise Linux (SLES) 12 SP2+ x64
  • 15. 15 RyuJIT RyuJIT is the x86 JIT in .NET Core 2.0 Open Source - RyuJIT is open source. JIT32 is not open source. Single JIT Codebase - There is now a single codebase for the CoreCLR JIT. This helps everyone who is working on platform expansion and who is investing in JIT improvements. An example is Samsung, who is investing in Linux x86 with RyuJIT x86. Performance - RyuJIT generally takes longer to compile than JIT32, but its optimizer can generate faster code. The performance difference may not be significant RyuJIT has more features than JIT32 https://github.com/dotnet/announcements/issues/10
  • 16. 16 dotnet restore I seguenti comandi vanno a richiamare dotnet restore: • new • run • build • publish • pack • test
  • 17. 17 Raspberry dotnet publish -c Release -r linux-arm Per eseguire correttamente una applicazione ARM su Raspberry, è necessario installare i prerequisiti del sistema. Per Raspberry (Debian STRETCH): sudo apt-get install curl libunwind8 gettext
  • 18. 18 Raspberry This library enables developers to use the various Raspberry Pi's hardware modules Pi.Camera Provides access to the offical Raspberry Pi Camera module. Pi.Info Provides information on this Raspberry Pi's CPU and form factor. Pi.Gpio Provides access to the Raspberry Pi's GPIO as a collection of GPIO Pins. Pi.Spi Provides access to the 2-channel SPI bus. Pi.I2c Provides access to the functionality of the i2c bus. Pi.Timing Provides access to The PI's Timing and threading API. Per copiare i file sul sistema Rasperry, è molto utile l’applicazione: WinSCP (https://winscp.net/) Per accedere ai PIN è possibile utilizzare dei progetti come: https://github.com/unosquare/raspberryio Sono presenti altri progetti simili. Microsoft non ha rilasciato nessuno strumento nativo per accedere ai PIN.
  • 19. Click to edit Master title style Demo ARM - IoT support
  • 20. ASP .NET CORE 2 NET CORE SPA Templates, Kestrel Improvements Razor C# 7.1, Razor Pages
  • 21. Click to edit Master title style “ ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern, cloud-based, Internet-connected applications - Microsoft
  • 22. 22 Timeline ASP .NET Core 1 ASP NET 5 Beta 6 27/7/2015 2 ASP NET 5 Beta 8 21/9/2015
  • 23. 4 Uscita tools in preview RC2 16/5/2016 5 Nascita di ASP .NET Core 1.0.0 27/6/2016 3 RC1 Nov 2015
  • 24. 7 2.0.0 14/8/2017 6 Tool definitivi 1.1.0 Nov 2016 ASP .NET Core 2.1.0 SignalR
  • 25. 25 ASP .NET 4.6 vs ASP .NET Core
  • 26. 26 Pipeline Uguale a quella del vecchio framework
  • 27. 27 Meta package <Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp2.0</TargetFramework> <MvcRazorCompileOnPublish>true</MvcRazorCompileOnPublish> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" /> </ItemGroup> </Project> Generando un nuovo progetto MVC con la versione 1.0 venivano inseriti ben 94 file, molti dei quali DLL. Allo stesso modo, con ASP .NET MVC Core 2 da 94 file e con l’utilizzo dei meta package siamo passi a 13 file. I benefici sono indiscutibili poichè l’ecosistema passa da 22MB a meno di 13MB
  • 29. Click to edit Master title style Demo SPA template
  • 30. 30 Additional template https://github.com/dotnet/templating https://github.com/dotnet/templating/wiki/Available-templates-for-dotnet-new http://dotnetnew.azurewebsites.net/ Per verificare i template installati sulla macchina (dotnet new --list) ASP.NET Core SPA Templates dotnet new -i "Microsoft.AspNetCore.SpaTemplates::*" ASP.NET Core Boilerplate dotnet new -i "Boilerplate.Templates::*" Auth0 Templates dotnet new -i "Auth0.Templates::*" AWS Lambda .NET Core Templates dotnet new -i "Amazon.Lambda.Templates::*" Cake.Frosting dotnet new -i "Cake.Frosting.Template::*" DotVVM dotnet new -i "DotVVM.Templates::*" IdentityServer4.Templates dotnet new -i "identityserver4.templates::*" Kentico Cloud Boilerplate dotnet new -i "KenticoCloud.CloudBoilerplateNet::*" Mono Game dotnet new -i "MonoGame.Template.NETCore::*" MSBuild extension dotnet new -i "MSBuildExtensionTemplate::*"
  • 31. 31 Additional template NancyFX Template not on nuget.org NSpec Templates dotnet new -i "dotnet-new-nspec::*" NUnit 3 Test Project Template dotnet new -i "NUnit3.DotNetNew.Template::*" Pioneer Console Boilerplate - Boilerplated .NET Core console application that includes dependency injection, logging and configuration. dotnet new -i "Pioneer.Console.Boilerplate::*" PowerShell Core dotnet new -i "FiftyProtons.Templates.PSCore::*" Prism Forms QuickStarts - Empty & QuickStart project Templates for Prism for Xamarin Forms. Requires dotnet cli 2.0 pre3+ dotnet new -i "Prism.Forms.QuickstartTemplates::*" Raspberry Pi 3 - C# template for .NET Core 2 IoT applications. dotnet new -i "RaspberryPi.Template::*" ServiceStack dotnet new -i "ServiceStack.Core.Templates::*" Template templates - Templates to create new project and item templates. Requires new3. dotnet new -i "FiftyProtons.Templates.DotNetNew::*"
  • 32. 32 In applicazioni ASP .NET Classiche, tutto viene ospitato in IIS Worker Process (w3wp.exe) IIS WebServer in vecchie applicazioni
  • 33. 33 Le applicazioni vengono eseguite in un processo console separato in cui viene eseguito il WebServer Kestrel. Questa infrastruttura ha pesantemente modificato le performance. Kestrel in ASP .NET Core
  • 34. 34 Kestrel in ASP .NET Core 2 Se l'applicazione accetta richieste solo da una rete interna, è possibile utilizzare Kestrel da solo. Se esegui la tua applicazione su Internet, devi utilizzare IIS, Nginx o Apache come reverse server proxy. Un server reverse proxy riceve le richieste HTTP da Internet e le trasmette a Kestrel dopo alcune manipolazioni preliminari. Uno scenario che richiede un reverse proxy è quando si dispone di più applicazioni che condividono lo stesso IP e la porta in esecuzione su un singolo server. Questo non funziona direttamente con Kestrel perché non supporta la condivisione dello stesso IP e della porta tra più processi. Kestrel gestisce tutto il traffico per quella porta indipendentemente dall'intestazione host
  • 35. 35 HttpSys in ASP .NET Core 2 (ex WebListener) HttpSys è una alternativa a Kestrel per le sole macchine Windows ed è possibile esporre l’applicazione ad internet. Può essere usata anche per applicazioni intranet. Non può essere utilizzato con IIS e IIS express. Non richiede un reverse proxy. HttpSys è una buona soluzione per applicazioni intranet che richiedono scenari non supportati da Kestrel, quali: Windows authentication HttpSys supports the following features: • Windows Authentication • Port sharing • HTTPS with SNI • HTTP/2 over TLS (Windows 10) • Direct file transmission • Response caching • WebSockets (Windows 8) Supported Windows versions: Windows 7 and Windows Server 2008 R2 and later
  • 36. 36 Kestrel improvement Miglioramenti sulle performance. In aggiunta sono state implementate nuove funzionalità come i limits. • Maximum Client Connections • Maximum Request Body Size • Maximum Request Body Data Rate Limitare il server Kestrel significa servire in maniera efficace i soli client che possono ricevere una risposta in tempi veloci. “Strozzare” sul nascere le connessioni dei client che non si riesce a servire, garantisce maggior efficacia per il webserver https://github.com/aspnet/KestrelHttpServer/blob/dev/src/Kestrel.Core/KestrelServerLimits.cs .UseKestrel(options => { options.Limits.MaxConcurrentConnections = 100; options.Limits.MaxConcurrentUpgradedConnections = 100; });
  • 37. 37 Kestrel improvement Plain text Plain Text Intended to highlight the HTTP efficiency of the server & stack. Implementations are free to cache the response body aggressively and remove/disable components that aren't required in order to maximize performance.
  • 38. 38 Kestrel improvement Plain Text with HTTP Pipelining
  • 39. 39 Kestrel improvement Plain Text with HTTP Pipelining https://blogs.msdn.microsoft.com/dotnet/2017/06/07/performance-improvements-in-net-core/ https://github.com/aspnet/benchmarks Like the Plain Text scenario above but with HTTP pipelining enabled at a depth of 16. Only stacks/servers that show an improvement with pipelining are included.
  • 40. 40 Kestrel nuova configurazione Nuova configurazione allo startup public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); }
  • 41. 41 Performance ASP .NET Core Gli assembly che fanno parte di ASP.NET Core sono stati pre-JITted, ovvero sono già pronti in linguaggio macchina per essere immediatamente eseguiti. Come conseguenza di ciò, l'applicazione ora si avvia in meno tempo ed il framework riesce a processare una quantità maggiore di richieste al secondo.
  • 42. 42 Razor Razor view pre-compilation is enabled during publish by default, reducing the publish output size and application startup time.
  • 43. 43 Migliorati il supporto ad HTTP Ora è possibile interpretare e utilizzare ETag o LastModified date sui contenuti trasmessi var data = Encoding.UTF8.GetBytes(“Sample text from a binary array"); var entityTag = new EntityTagHeaderValue(""MyEtagValue""); return File(data, "text/plain", "downloadName.txt", lastModified: DateTime.UtcNow.AddSeconds(-5), entityTag: entityTag);
  • 44. 44 Razor e C# 7.1 Razor si adegua alla sistassi C# 7.1 Per abilitare la nuova sintassi C# è necessario modificare il .CSPROJ con il tag: <LangVersion>latest</LangVersion>
  • 45. Click to edit Master title style Demo C# 7.1
  • 46. 46 Razor e C# 7.1 Default Literal Expressions int i = default(int); // Current int i = default; // New var i = default; // Error: no target type const string S = null; const string S = default; const int? NI = null; // error const int? NI = default; // error
  • 47. 47 Razor e C# 7.1 Default Literal Expressions void M(MyStruct ms = default) { ... } bool b = null is T; // allowed, always false if (0 is int) { ... } // True: 0 is an int if (default(int) is int) { ... } // True: 0 is still an int if (default is int) { ... } // Would be false! default(object) is null, which is not an int. Func<string, bool> whereClause = default(Func<string, bool>); Si può omettere l’operatore di destra Func<string, bool> whereClause = default;
  • 48. 48 Razor e C# 7.1 Infer tuple names Action y = () => M(); var t = (x: x, y); t.y(); // this might have previously picked up an extension method called “y”, but would now call the lambda. Tuple Design: https://github.com/dotnet/roslyn/blob/master/docs/features/tuples.md int count = 5; string label = "Colors used in the map"; var pair = (count, label); // element names are "count" and "label"
  • 49. 49 C# 7.1 Async Main public static void Main() { MainAsync().GetAwaiter().GetResult(); } private static async Task MainAsync() { ... // Main body here }
  • 50. 50 C# 7.1 Pattern Matching With Generics public double Area<T>(T shape) where T : Shape { double calculatedArea = 0.0d; switch (shape) { case Circle circle: calculatedArea = circle.Area(); break; case Sphere sphere: calculatedArea = sphere.Area(); break; } return calculatedArea; } public abstract class Shape { public double Radius { get; set; } public abstract double Area(); } public class Circle : Shape { public override double Area() { return Math.PI * Math.Pow(Radius, 2); } } public class Sphere : Shape { public override double Area() { return 4 * Math.PI * Math.Pow(Radius, 2); } }
  • 51. 51 Razor Pages Ciascuna Razor Page è un'unità autonoma della nostra applicazione web e la si riconosce dalle seguenti caratteristiche: • Contiene una direttiva @page in cima al file. Questo serve a designarla come una Razor Page e a configurare il routing affinché sia direttamente invocabile via URL. Una Razor Page situata in /Pages/Products.cshtml sarà raggiungibile dall'URL /Products; • Può contenere un blocco @functions all'interno del qual definiremo il code behind della pagina, ovvero proprietà e metodi che potranno essere richiamati dalla Razor Page. Come in ASP.NET WebForms, il code behind può anche essere posto in un file di codice separato che ha estensione .cshtml.cs. In questo caso, il file di codice dovrà contenere una classe che deriva da PageModel; • I tag helper <form> si arricchiscono degli attributi asp-page e asp-page-handler che permettono di indicare il nome della pagina che riceverà i dati del form e della function definita in essa; • Definendo metodi dai nomi speciali come OnGet, OnGetAsync, OnPost o OnPostAsync potremo eseguire del codice quando la pagina viene richiamata con i metodi HTTP GET o POST. Tali metodi sono equivalenti ad action di ASP.NET MVC decorate con gli attributi HttpGet o HttpPost; • Può contenere direttive @inject che usiamo per ottenere istanze di servizi grazie al meccanismo di dependency injection di ASP.NET Core.
  • 53. 53 Razor Pages – Elementi distintivi Parametri @page "{id:int}" public async Task<IActionResult> OnGetAsync(int id) { … } https://docs.microsoft.com/en-us/aspnet/core/mvc/razor-pages/ Proprietà del modello [BindProperty] public int PageDataID { get; set; } [BindProperty] public string Title { get; set; }Tipi di ritorno return Page(); return RedirectToPage("/");
  • 55. Click to edit Master title style Demo Razor Pages e Blog template
  • 56. 56 WebAssembly MONO Project We have been experimenting with a couple of approaches to bring Mono to the web using WebAssembly - a technology that can efficiently and safely execute code in web browsers without being limited to Javascript. Running code written in C or C++ inside the browser has been a big motivator, but most major programming languages have plans to target WebAssembly as a platform. WebAssembly has been out for a few months on desktop computers and Android, and with the introduction of iOS 11 it will become nearly universal. Miguel de Icaza http://www.mono-project.com/news/2017/08/09/hello-webassembly/
  • 57. 57 WebAssembly Blazor An experimental web UI framework using C#/Razor and HTML, running client-side via WebAssembly The arrival of WebAssembly creates the possibility of building client-side web applications using languages and runtimes that are more typically used for native app development. Blazor runs .NET code in the browser via a small, portable .NET runtime called DotNetAnywhere (DNA) compiled to WebAssembly. The programming model will be familiar to anyone who's worked with Razor (the C#/HTML page format used by ASP.NET MVC and ASP.NET Pages). https://github.com/SteveSanderson/Blazor
  • 58. .NET Standard 2 NET CORE WCF, Nuget Package, Xamarin support
  • 59. 59 Il futuro: .NET Standard
  • 60. 60 .NET Standard 2.0 Nuove funzionalità Bigger API Surface: We have more than doubled the set of available APIs from 13k in .NET Standard 1.6 to 32k in .NET Standard 2.0. Most of the added APIs are .NET Framework APIs. These additions make it much easier to port existing code to .NET Standard, and, by extension, to any .NET implementation of .NET Standard, such as .NET Core 2.0 and the upcoming version of UWP. .NET Framework compatibility mode: The vast majority of NuGet packages are currently still targeting .NET Framework. Many projects are currently blocked from moving to .NET Standard because not all their dependencies are targeting .NET Standard yet. That's why we added a compatibility mode that allows .NET Standard projects to depend on .NET Framework libraries as if they were compiled for .NET Standard. Of course, this may not work in all cases (for instance, if the .NET Framework binaries uses WPF), but we found that 70% of all NuGet packages on nuget.org are API compatible with .NET Standard 2.0, so in practice it unblocks many projects. Broad platform support. .NET Standard 2.0 is supported on the following platforms: • .NET Framework 4.6.1 • .NET Core 2.0 • Mono 5.4 • Xamarin.iOS 10.14 • Xamarin.Mac 3.8 • Xamarin.Android 7.5 • UWP is work in progress and will ship later this year.
  • 61. 61 Nuget "We are happy to announce an update to the NuGet client that comes bundled with Visual Studio 2017 version 15.3 RTW and .NET Core 2.0 SDK,“ NuGet said : "This release introduces support for new scenarios such as .NET Core 2.0/.NET Standard 2.0, some new features, a series of bug fixes and performance improvements." Microsoft earlier pointed out that a May investigation found some 70 percent of NuGet packages (which manages more than 87,000 unique packages and more than 960,000 package versions) were compatible with .NET Standard 2.0. The vast majority of NuGet packages are currently still targeting .NET Framework. Many projects are currently blocked from moving to .NET Standard because not all their dependencies are targeting .NET Standard yet. That's why we added a compatibility mode that allows .NET Standard projects to depend on .NET Framework libraries as if they were compiled for .NET Standard. NuGet 4.0+ uses at least two global package locations: User-specific: %userprofile%.nugetpackages Machine-wide: %ProgramFiles(x86)%Microsoft SDKsNuGetPackages
  • 64. 64 .NET Standard 2.0 Nuove funzionalità
  • 65. 65 How does .NET Standard work? .NET Standard is represented by • The NuGet package NetStandard.Library which contains • The reference assembly netstandard.dll At build time • .NET Standard bridges references to existing .NET Framework and PCL assemblies via type forwarding At runtime • Each platform provides an implementation for netstandard.dll that type forwards to its implementation
  • 66. 66 Type Forwarding? Type forwarding allows you to move a type to another assembly without having to recompile applications that use the original assembly. https://docs.microsoft.com/en-us/dotnet/framework/app-domains/type-forwarding-in-the- common-language-runtime https://www.youtube.com/watch?v=vg6nR7hS2lI
  • 67. Click to edit Master title styleWhat can you reference from .NET Standard? My Standard Library 2.x .NET Standard Library .NET Framework LibraryPortable Class Library .NET FRAMEWORK .NET CORE XAMARIN Via Portability Via Compatibility Shim Legend Application Type Is able to reference
  • 68. Click to edit Master title style.NET Standard under the hood - BUILD TYPE FORWARDING netstandard!Object mscorlib!Object This happens when you build a .NET Standard-based Library
  • 69. Click to edit Master title style.NET Standard under the hood - LOAD TYPE FORWARDING This happens when you load .NET Standard-based library
  • 70. Click to edit Master title style Demo SharpZipLib
  • 71. 71 WCF Client Proxy System.ServiceModel.Duplex 4.4.0 WCF .NET Core System.ServiceModel.Http 4.4.0 System.ServiceModel.NetTcp 4.4.0 System.ServiceModel.Primitives 4.4.0 System.ServiceModel.Security 4.4.0 WCF Connected Service Provider E’ possibile referenziare un servizio WCF. Non è possibile creare un nuovo progetto di tipo WCF. Risulta necessario avere un progetto .NET Standard > 2.0 La possibilità di utilizzare e referenziare progetti di tipo WCF è possibile grazione al WCF Connected Service Provider che ci consente di generare i proxy per le classi del WCF https://marketplace.visualstudio.com/items?itemName=WCFCORETEAM.VisualStudioWCFConnectedService
  • 72. Click to edit Master title style Demo WCF Service Reference
  • 73. 73 Microsoft.Data.SQLite Microsoft.Data.Sqlite provides SQLite implementations of the System.Data.Common interfaces. It is designed to work with the native, C library "sqlite3" on all platforms where .NET Core and .NET Framework are supported, including Windows, Linux, macOS, and others. The good thing about this library is, it’s build for .NET Core, meaning you can develop and run applications on Windows and non-Windows platform (Mac, Linux) supporting .NET Core Runtime.
  • 75. 75 Xamarin Roadmap 2.4 Xamarin.Forms for macOS Preview vNext (est. Q4 2017) Xamarin.Forms for GTK# Preview Deprecation of WP8.0 and 8.1 vNext2 (est. Q1 2018) Xamarin.Forms for GTK# Xamarin.Forms for macOS https://forums.xamarin.com/discussion/85747/xamarin-forms-feature-roadmap/p1
  • 76. Entity Framework Core 2 NET CORE Context Pool, View, Like function String interpolations, Scalar function mapping, Query filter - soft delete, Manual compiled queries
  • 78. 78 EF Core • It would work on all operating systems (Linux, Mac) and platforms (Windows Phone, Windows Store) supported by .NET Core • Non-relational databases would also be supported, making it not just an ORM: Azure Table Storage and Redis were the first to be announced • Fully extensible and provider-based • A simplified API that is close to the previous one • New features: shadow properties, ability to mix SQL with LINQ, transparent client-side function evaluation, high-low identifier generation, batching of queries, improved SQL generation Support for providers other than SQL Server (SQL Server Compact Edition, SQLite, InMemory, PostgreSQL, MySQL, DB2, MyCat, Oracle)
  • 79. 79 Table splitting It is now possible to map two or more entity types to the same table where the primary key column(s) will be shared and each row will correspond to two or more entities. modelBuilder.Entity<Product>() .HasOne(e => e.Details) .WithOne(e => e.Product) .HasForeignKey<ProductDetails>(e => e.Id); modelBuilder.Entity<Product>().ToTable("Products"); modelBuilder.Entity<ProductDetails>().ToTable("Products");
  • 80. 80 Owned types An owned entity type can share the same CLR type with another owned entity type, but since it cannot be identified just by the CLR type there must be a navigation to it from another entity type. The entity containing the defining navigation is the owner. When querying the owner the owned types will be included by default. public class Order { public int Id { get; set; } public OrderDetails OrderDetails { get; set; } } public class OrderDetails { public StreetAddress BillingAddress { get; set; } public StreetAddress ShippingAddress { get; set; } } modelBuilder.Entity<Order>().OwnsOne(p => p.OrderDetails, cb => { cb.OwnsOne(c => c.BillingAddress); cb.OwnsOne(c => c.ShippingAddress); }); public class StreetAddress { public string Street { get; set; } public string City { get; set; } }
  • 81. 81 Model-level query filters This feature allows LINQ query predicates (a boolean expression typically passed to the LINQ Where query operator) to be defined directly on Entity Types in the metadata model (usually in OnModelCreating). Such filters are automatically applied to any LINQ queries involving those Entity Types, including Entity Types referenced indirectly, such as through the use of Include or direct navigation property references. Some common applications of this feature are: 1. Soft delete - An Entity Types defines an IsDeleted property. 2. Multi-tenancy - An Entity Type defines a TenantId property. public class BloggingContext : DbContext { public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; } public int TenantId {get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Post>().HasQueryFilter( p => !p.IsDeleted && p.TenantId == this.TenantId ); } } Limitations Navigation references are not allowed. This feature may be added based on feedback. Filters can only be defined on the root Entity Type of a hierarchy.
  • 82. 82 Scalar function mapping Once a method has been registered you can use it anywhere in your queries. 1. By convention the name of the method is used as the name of a function (in this case a user defined function) when generating the SQL, but you can override the name and schema during method registration 2. Currently only scalar functions are supported 3. You must create the mapped function in the database, e.g. EF Core migrations will not take care of creating it public class BloggingContext : DbContext { [DbFunction] public static int PostReadCount(int blogId) { throw new Exception(); } } var query = from p in context.Posts where BloggingContext.PostReadCount(p.Id) > 5 select p;
  • 83. 83 Self-contained type configuration for code first In EF6 it was possible to encapsulate the code first configuration of a specific entity type by deriving from EntityTypeConfiguraiton. In EF Core 2.0 we are bringing this pattern back: class CustomerConfiguration : IEntityTypeConfiguration<Customer> { public void Configure(EntityTypeBuilder<Customer> builder) { builder.HasKey(c => c.AlternateKey); builder.Property(c => c.Name).HasMaxLength(200); } } ... // OnModelCreating builder.ApplyConfiguration(new CustomerConfiguration());
  • 84. 84
  • 85. 85 DbContext pooling If this method is used, at the time a DbContext instance is requested by a controller we will first check if there is an instance available in the pool. Once the request processing finalizes, any state on the instance is reset and the instance is itself returned to the pool. This is conceptually similar to how connection pooling operates in ADO.NET providers and has the advantage of saving some of the cost of initialization of DbContext instance. services.AddDbContextPool<BloggingContext>(options => options.UseSqlServer(connectionString)); Avoid using DbContext Pooling if you maintain your own state (e.g. private fields) in your derived DbContext class that should not be shared across requests. EF Core will only reset the state that is aware of before adding a DbContext instance to the pool.
  • 86. 86 Explicitly compiled queries Although in general EF Core can automatically compile and cache queries based on a hashed representation of the query expressions, this mechanism can be used to obtain a small performance gain by bypassing the computation of the hash and the cache lookup, allowing the application to use an already compiled query through the invocation of a delegate. // Create an explicitly compiled query private static Func<CustomerContext, int, Customer> _customerById = EF.CompileQuery((CustomerContext db, int id) => db.Customers .Include(c => c.Address) .Single(c => c.Id == id)); // Use the compiled query by invoking it using (var db = new CustomerContext()) { var customer = _customerById(db, 147); }
  • 87. 87 String interpolation C# 6 introduced String Interpolation, a feature that allows C# expressions to be directly embedded in string literals, providing a nice way of building strings at runtime. In EF Core 2.0 we added special support for interpolated strings to our two primary APIs that accept raw SQL strings: FromSql and ExecuteSqlCommand. This new support allows C# string interpolation to be used in a 'safe' manner. in a way that protects against common SQL injection mistakes that can occur when dynamically constructing SQL at runtime. var city = "London"; var contactTitle = "Sales Representative"; using (var context = CreateContext()) { context.Set<Customer>() .FromSql($@" SELECT * FROM ""Customers"" WHERE ""City"" = {city} AND ""ContactTitle"" = {contactTitle}") .ToArray(); } @p0='London' (Size = 4000) @p1='Sales Representative' (Size = 4000) SELECT * FROM ""Customers"" WHERE ""City"" = @p0 AND ""ContactTitle"" = @p1
  • 88. 88 EF.Functions.Like() We have added the EF.Functions property which can be used by EF Core or providers to define methods that map to database functions or operators so that those can be invoked in LINQ queries. Note that Like() comes with an in-memory implementation, which can be handy when working against an in- memory database or when evaluation of the predicate needs to occur con the client side. var aCustomers = from c in context.Customers where EF.Functions.Like(c.Name, "a%"); select c; @p0='London' (Size = 4000) @p1='Sales Representative' (Size = 4000) SELECT * FROM ""Customers"" WHERE ""City"" = @p0 AND ""ContactTitle"" = @p1
  • 89. 89 EF Core Power Tools Reverse Engineer - Generate POCO classes, derived DbContext and mapping for an existing database. EF Core allows you to use the Scaffold-DbContext or the dotnet ef dbcontext scaffold commands to reverse engineer a database and create entity and DbContext classes for your database tables. https://github.com/ErikEJ/SqlCeToolbox/wiki/EF-Core-Power-Tools (Erik Ejlskov Jensen) ErikEJ
  • 91. 91 Roadmap EF Core 2.1 EntityFrameworkCore 2.1.0 Group By
  • 92. 92 Cosa manca? • View • Lazy loading • many-to-many collections and no inheritance strategies, only single table inheritance • database initializers and the capability to seed the database • No interception capabilities • Stored procedures for Create-Update-Delete (CUD) operations is also not yet implemented. It is possible to use stored procedures for querying • It is not possible yet to plug our own custom conventions • Spatial types • not possible to reverse-engineer (official) EF Core is not ready for enterprise-level usage Dapper ServiceStack.OrmLite
  • 94. 94 Nov 15 Marco Zamana: Visual Studio Team Service Andrea Tosato: Azure Functions