SlideShare ist ein Scribd-Unternehmen logo
1 von 95
.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

Weitere ähnliche Inhalte

Was ist angesagt?

Red Hat Forum Benelux 2015
Red Hat Forum Benelux 2015Red Hat Forum Benelux 2015
Red Hat Forum Benelux 2015Microsoft
 
Integrating Linux Systems with Active Directory Using Open Source Tools
Integrating Linux Systems with Active Directory Using Open Source ToolsIntegrating Linux Systems with Active Directory Using Open Source Tools
Integrating Linux Systems with Active Directory Using Open Source ToolsAll Things Open
 
Leveraging CI/CD to improve open stack operation
Leveraging CI/CD to improve open stack operationLeveraging CI/CD to improve open stack operation
Leveraging CI/CD to improve open stack operationMaría Angélica Bracho
 
カエルと実践するコンテナ
カエルと実践するコンテナカエルと実践するコンテナ
カエルと実践するコンテナTsuyoshi Miyake
 
[OpenStack 하반기 스터디] Interoperability with ML2: LinuxBridge, OVS and SDN
[OpenStack 하반기 스터디] Interoperability with ML2: LinuxBridge, OVS and SDN[OpenStack 하반기 스터디] Interoperability with ML2: LinuxBridge, OVS and SDN
[OpenStack 하반기 스터디] Interoperability with ML2: LinuxBridge, OVS and SDNOpenStack Korea Community
 
Elasticsearch Monitoring in Openshift
Elasticsearch Monitoring in OpenshiftElasticsearch Monitoring in Openshift
Elasticsearch Monitoring in OpenshiftLukas Vlcek
 
Introdot Netc Sharp En
Introdot Netc Sharp EnIntrodot Netc Sharp En
Introdot Netc Sharp EnGregory Renard
 
Deploying vn fs with kubernetes pods and vms
Deploying vn fs with kubernetes pods and vmsDeploying vn fs with kubernetes pods and vms
Deploying vn fs with kubernetes pods and vmsLibbySchulze1
 
JDO 2019: What you should be aware of before setting up kubernetes on premise...
JDO 2019: What you should be aware of before setting up kubernetes on premise...JDO 2019: What you should be aware of before setting up kubernetes on premise...
JDO 2019: What you should be aware of before setting up kubernetes on premise...PROIDEA
 
OSDC 2018 | Hardware-level data-center monitoring with Prometheus by Conrad H...
OSDC 2018 | Hardware-level data-center monitoring with Prometheus by Conrad H...OSDC 2018 | Hardware-level data-center monitoring with Prometheus by Conrad H...
OSDC 2018 | Hardware-level data-center monitoring with Prometheus by Conrad H...NETWAYS
 
What's new in python 3.8? | Python 3.8 New Features | Edureka
What's new in python 3.8? | Python 3.8 New Features | EdurekaWhat's new in python 3.8? | Python 3.8 New Features | Edureka
What's new in python 3.8? | Python 3.8 New Features | EdurekaEdureka!
 
Elk for applications on k8s
Elk for applications on k8sElk for applications on k8s
Elk for applications on k8sChe-Chia Chang
 
Securing the Software Supply Chain with TUF and Docker - Justin Cappos and Sa...
Securing the Software Supply Chain with TUF and Docker - Justin Cappos and Sa...Securing the Software Supply Chain with TUF and Docker - Justin Cappos and Sa...
Securing the Software Supply Chain with TUF and Docker - Justin Cappos and Sa...Docker, Inc.
 
O'Reilly Software Architecture Conference London 2017: Building Resilient Mic...
O'Reilly Software Architecture Conference London 2017: Building Resilient Mic...O'Reilly Software Architecture Conference London 2017: Building Resilient Mic...
O'Reilly Software Architecture Conference London 2017: Building Resilient Mic...Ambassador Labs
 
OpenShift 4 installation
OpenShift 4 installationOpenShift 4 installation
OpenShift 4 installationRobert Bohne
 
Cloud networking deep dive
Cloud networking deep diveCloud networking deep dive
Cloud networking deep diveamylynn11
 
OpenShift Origin Internals
OpenShift Origin Internals OpenShift Origin Internals
OpenShift Origin Internals OpenShift Origin
 
OSDC 2018 | Highly Available Cloud Foundry on Kubernetes by Cornelius Schumacher
OSDC 2018 | Highly Available Cloud Foundry on Kubernetes by Cornelius SchumacherOSDC 2018 | Highly Available Cloud Foundry on Kubernetes by Cornelius Schumacher
OSDC 2018 | Highly Available Cloud Foundry on Kubernetes by Cornelius SchumacherNETWAYS
 

Was ist angesagt? (20)

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

Ähnlich wie NET core 2 e i fratelli

.Net: Introduction, trends and future
.Net: Introduction, trends and future.Net: Introduction, trends and future
.Net: Introduction, trends and futureBishnu Rawal
 
What should you know about Net Core?
What should you know about Net Core?What should you know about Net Core?
What should you know about Net Core?Damir Dobric
 
ASP.NET Core: The best of the new bits
ASP.NET Core: The best of the new bitsASP.NET Core: The best of the new bits
ASP.NET Core: The best of the new bitsKen Cenerelli
 
.NET framework vs .net core 3.1 commons &amp; differences
 .NET framework vs .net core 3.1  commons &amp; differences .NET framework vs .net core 3.1  commons &amp; differences
.NET framework vs .net core 3.1 commons &amp; differencesAlina Vilk
 
Visual studio 2015 and .net core 5 – get ready to rumble
Visual studio 2015 and .net core 5  – get ready to rumbleVisual studio 2015 and .net core 5  – get ready to rumble
Visual studio 2015 and .net core 5 – get ready to rumbleTadeusz Balcer
 
Pottnet Meetup Essen - ASP.Net Core
Pottnet Meetup Essen - ASP.Net CorePottnet Meetup Essen - ASP.Net Core
Pottnet Meetup Essen - ASP.Net CoreMalte Lantin
 
NET app modernization and Microsoft Azure.pptx
NET app modernization and Microsoft Azure.pptxNET app modernization and Microsoft Azure.pptx
NET app modernization and Microsoft Azure.pptxNishitPatel409228
 
Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele RialdiCodeFest
 
Install .Net Core, SQL Server V-Next on Linux and deploy .Net core applicatio...
Install .Net Core, SQL Server V-Next on Linux and deploy .Net core applicatio...Install .Net Core, SQL Server V-Next on Linux and deploy .Net core applicatio...
Install .Net Core, SQL Server V-Next on Linux and deploy .Net core applicatio...Ajith Ramawickrama
 
JS digest. November 2017
JS digest. November 2017JS digest. November 2017
JS digest. November 2017ElifTech
 
.NET MeetUp Prague 2017 - .NET Standard -- Karel Zikmund
.NET MeetUp Prague 2017 - .NET Standard -- Karel Zikmund.NET MeetUp Prague 2017 - .NET Standard -- Karel Zikmund
.NET MeetUp Prague 2017 - .NET Standard -- Karel ZikmundKarel Zikmund
 
Academy PRO: .NET Core intro
Academy PRO: .NET Core introAcademy PRO: .NET Core intro
Academy PRO: .NET Core introBinary Studio
 
ASP.NET 5 - Microsoft's Web development platform reimagined
ASP.NET 5 - Microsoft's Web development platform reimaginedASP.NET 5 - Microsoft's Web development platform reimagined
ASP.NET 5 - Microsoft's Web development platform reimaginedAlex Thissen
 
Microsoft .NET 6 -What's All About The New Update
Microsoft .NET 6 -What's All About The New UpdateMicrosoft .NET 6 -What's All About The New Update
Microsoft .NET 6 -What's All About The New UpdateAdam John
 
tybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notestybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notesWE-IT TUTORIALS
 
.NET Core Apps: Design & Development
.NET Core Apps: Design & Development.NET Core Apps: Design & Development
.NET Core Apps: Design & DevelopmentGlobalLogic Ukraine
 
About .NET 8 and a first glimpse into .NET9
About .NET 8 and a first glimpse into .NET9About .NET 8 and a first glimpse into .NET9
About .NET 8 and a first glimpse into .NET9Jürgen Gutsch
 

Ähnlich wie NET core 2 e i fratelli (20)

.Net: Introduction, trends and future
.Net: Introduction, trends and future.Net: Introduction, trends and future
.Net: Introduction, trends and future
 
What should you know about Net Core?
What should you know about Net Core?What should you know about Net Core?
What should you know about Net Core?
 
.net core
.net core.net core
.net core
 
ASP.NET Core: The best of the new bits
ASP.NET Core: The best of the new bitsASP.NET Core: The best of the new bits
ASP.NET Core: The best of the new bits
 
.NET framework vs .net core 3.1 commons &amp; differences
 .NET framework vs .net core 3.1  commons &amp; differences .NET framework vs .net core 3.1  commons &amp; differences
.NET framework vs .net core 3.1 commons &amp; differences
 
Visual studio 2015 and .net core 5 – get ready to rumble
Visual studio 2015 and .net core 5  – get ready to rumbleVisual studio 2015 and .net core 5  – get ready to rumble
Visual studio 2015 and .net core 5 – get ready to rumble
 
Pottnet Meetup Essen - ASP.Net Core
Pottnet Meetup Essen - ASP.Net CorePottnet Meetup Essen - ASP.Net Core
Pottnet Meetup Essen - ASP.Net Core
 
NET app modernization and Microsoft Azure.pptx
NET app modernization and Microsoft Azure.pptxNET app modernization and Microsoft Azure.pptx
NET app modernization and Microsoft Azure.pptx
 
.NET Overview & Roadmap
.NET Overview & Roadmap.NET Overview & Roadmap
.NET Overview & Roadmap
 
Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele Rialdi
 
Install .Net Core, SQL Server V-Next on Linux and deploy .Net core applicatio...
Install .Net Core, SQL Server V-Next on Linux and deploy .Net core applicatio...Install .Net Core, SQL Server V-Next on Linux and deploy .Net core applicatio...
Install .Net Core, SQL Server V-Next on Linux and deploy .Net core applicatio...
 
.Net Core
.Net Core.Net Core
.Net Core
 
JS digest. November 2017
JS digest. November 2017JS digest. November 2017
JS digest. November 2017
 
.NET MeetUp Prague 2017 - .NET Standard -- Karel Zikmund
.NET MeetUp Prague 2017 - .NET Standard -- Karel Zikmund.NET MeetUp Prague 2017 - .NET Standard -- Karel Zikmund
.NET MeetUp Prague 2017 - .NET Standard -- Karel Zikmund
 
Academy PRO: .NET Core intro
Academy PRO: .NET Core introAcademy PRO: .NET Core intro
Academy PRO: .NET Core intro
 
ASP.NET 5 - Microsoft's Web development platform reimagined
ASP.NET 5 - Microsoft's Web development platform reimaginedASP.NET 5 - Microsoft's Web development platform reimagined
ASP.NET 5 - Microsoft's Web development platform reimagined
 
Microsoft .NET 6 -What's All About The New Update
Microsoft .NET 6 -What's All About The New UpdateMicrosoft .NET 6 -What's All About The New Update
Microsoft .NET 6 -What's All About The New Update
 
tybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notestybsc it asp.net full unit 1,2,3,4,5,6 notes
tybsc it asp.net full unit 1,2,3,4,5,6 notes
 
.NET Core Apps: Design & Development
.NET Core Apps: Design & Development.NET Core Apps: Design & Development
.NET Core Apps: Design & Development
 
About .NET 8 and a first glimpse into .NET9
About .NET 8 and a first glimpse into .NET9About .NET 8 and a first glimpse into .NET9
About .NET 8 and a first glimpse into .NET9
 

Mehr von Andrea Tosato

Codemotion Azure Container Apps
Codemotion Azure Container AppsCodemotion Azure Container Apps
Codemotion Azure Container AppsAndrea Tosato
 
Azure Static Web Apps & Blazor
Azure Static Web Apps & BlazorAzure Static Web Apps & Blazor
Azure Static Web Apps & BlazorAndrea Tosato
 
How to develop modern web application, with no money and nod javascript
How to develop modern web application, with no money and nod javascriptHow to develop modern web application, with no money and nod javascript
How to develop modern web application, with no money and nod javascriptAndrea Tosato
 
Entity framework core v3 from sql to no sql
Entity framework core v3 from sql to no sqlEntity framework core v3 from sql to no sql
Entity framework core v3 from sql to no sqlAndrea Tosato
 
How to develop modern web application - With no money and no Javascript
How to develop modern web application - With no money and no JavascriptHow to develop modern web application - With no money and no Javascript
How to develop modern web application - With no money and no JavascriptAndrea Tosato
 
Mixing Identity server, AAD, ASP .NET Identity
Mixing Identity server, AAD, ASP .NET IdentityMixing Identity server, AAD, ASP .NET Identity
Mixing Identity server, AAD, ASP .NET IdentityAndrea Tosato
 
An introduction to GraphQL in .NET Core
An introduction to GraphQL in .NET CoreAn introduction to GraphQL in .NET Core
An introduction to GraphQL in .NET CoreAndrea Tosato
 
Cost Optimization - Global Azure Bootcamp 2019
Cost Optimization - Global Azure Bootcamp 2019Cost Optimization - Global Azure Bootcamp 2019
Cost Optimization - Global Azure Bootcamp 2019Andrea Tosato
 
Deep Dive Azure Functions - Global Azure Bootcamp 2019
Deep Dive Azure Functions - Global Azure Bootcamp 2019Deep Dive Azure Functions - Global Azure Bootcamp 2019
Deep Dive Azure Functions - Global Azure Bootcamp 2019Andrea Tosato
 
Azure Function Workflow
Azure Function WorkflowAzure Function Workflow
Azure Function WorkflowAndrea Tosato
 
Azure Cognitive Service on Container
Azure Cognitive Service on ContainerAzure Cognitive Service on Container
Azure Cognitive Service on ContainerAndrea Tosato
 
Deploy multi-environment application with Azure DevOps
Deploy multi-environment application with Azure DevOpsDeploy multi-environment application with Azure DevOps
Deploy multi-environment application with Azure DevOpsAndrea Tosato
 
Azure Cognitive Service in Container
Azure Cognitive Service in ContainerAzure Cognitive Service in Container
Azure Cognitive Service in ContainerAndrea Tosato
 
Azure Signalr Service
Azure Signalr ServiceAzure Signalr Service
Azure Signalr ServiceAndrea Tosato
 
Xamarin - Microcharts
Xamarin - MicrochartsXamarin - Microcharts
Xamarin - MicrochartsAndrea Tosato
 
Introduzione Xamarin
Introduzione XamarinIntroduzione Xamarin
Introduzione XamarinAndrea Tosato
 

Mehr von Andrea Tosato (20)

Codemotion Azure Container Apps
Codemotion Azure Container AppsCodemotion Azure Container Apps
Codemotion Azure Container Apps
 
Lite db for dummies
Lite db for dummiesLite db for dummies
Lite db for dummies
 
Azure Static Web Apps & Blazor
Azure Static Web Apps & BlazorAzure Static Web Apps & Blazor
Azure Static Web Apps & Blazor
 
Dapr logicapps
Dapr logicappsDapr logicapps
Dapr logicapps
 
How to develop modern web application, with no money and nod javascript
How to develop modern web application, with no money and nod javascriptHow to develop modern web application, with no money and nod javascript
How to develop modern web application, with no money and nod javascript
 
Entity framework core v3 from sql to no sql
Entity framework core v3 from sql to no sqlEntity framework core v3 from sql to no sql
Entity framework core v3 from sql to no sql
 
How to develop modern web application - With no money and no Javascript
How to develop modern web application - With no money and no JavascriptHow to develop modern web application - With no money and no Javascript
How to develop modern web application - With no money and no Javascript
 
Mixing Identity server, AAD, ASP .NET Identity
Mixing Identity server, AAD, ASP .NET IdentityMixing Identity server, AAD, ASP .NET Identity
Mixing Identity server, AAD, ASP .NET Identity
 
An introduction to GraphQL in .NET Core
An introduction to GraphQL in .NET CoreAn introduction to GraphQL in .NET Core
An introduction to GraphQL in .NET Core
 
DevOps Heroes 2019
DevOps Heroes 2019DevOps Heroes 2019
DevOps Heroes 2019
 
dotNetConf2019
dotNetConf2019dotNetConf2019
dotNetConf2019
 
Cost Optimization - Global Azure Bootcamp 2019
Cost Optimization - Global Azure Bootcamp 2019Cost Optimization - Global Azure Bootcamp 2019
Cost Optimization - Global Azure Bootcamp 2019
 
Deep Dive Azure Functions - Global Azure Bootcamp 2019
Deep Dive Azure Functions - Global Azure Bootcamp 2019Deep Dive Azure Functions - Global Azure Bootcamp 2019
Deep Dive Azure Functions - Global Azure Bootcamp 2019
 
Azure Function Workflow
Azure Function WorkflowAzure Function Workflow
Azure Function Workflow
 
Azure Cognitive Service on Container
Azure Cognitive Service on ContainerAzure Cognitive Service on Container
Azure Cognitive Service on Container
 
Deploy multi-environment application with Azure DevOps
Deploy multi-environment application with Azure DevOpsDeploy multi-environment application with Azure DevOps
Deploy multi-environment application with Azure DevOps
 
Azure Cognitive Service in Container
Azure Cognitive Service in ContainerAzure Cognitive Service in Container
Azure Cognitive Service in Container
 
Azure Signalr Service
Azure Signalr ServiceAzure Signalr Service
Azure Signalr Service
 
Xamarin - Microcharts
Xamarin - MicrochartsXamarin - Microcharts
Xamarin - Microcharts
 
Introduzione Xamarin
Introduzione XamarinIntroduzione Xamarin
Introduzione Xamarin
 

Kürzlich hochgeladen

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 

Kürzlich hochgeladen (20)

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 

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