SlideShare a Scribd company logo
Киев 2017
Только реальные кейсы. Только актуальные тренды.
Architecture &
Development of .NET Core
Applications
Andrey Antilikatorov
Киев 2017Architecture & Development of .NET Core Applications
Киев 2017Architecture & Development of .NET Core Applications
Киев 2017
Analytics says…
.NET Core will be as popular as Ruby and
NodeJS.
.NET Core and NodeJS will be the most popular
platforms for back-end solution compete on the
market.
In few years .NET Core (not Java) will be
number one choice for enterprise-level
applications.
Architecture & Development of .NET Core Applications
.Net Core, Java, NodeJS…
Киев 2017Architecture & Development of .NET Core Applications
Киев 2017
.NET Core :: Few Things
• Many mechanisms such as authentication, security,
component interactions now changed comparing to .Net
Framework.
• Many components and platforms (for example for
Desktop applications) are missing.
• Nevertheless, .NET Core provides corporate-level
software benefits for small projects.
Architecture & Development of .NET Core Applications
Киев 2017
.Net Core vs .Net Framework
• There are cross-platform needs.
• Application architecture is based
on microservices.
• Scalability and high performance
are the must. Need to get as
much as possible out of the box.
• Need to use both Linux and
Windows containers.
• You are running multiple .NET
versions side-by-side.
• Opensource framework is
required.
Architecture & Development of .NET Core Applications
• Application currently uses .NET
Framework and has strong
dependencies on Windows.
• Need to use Windows APIs that
are not supported by .NET Core.
• Need to use third-party libraries
or NuGet packages that are not
available for .NET Core.
• Need tools, technologies or
platforms not supported by .NET
Core.
.NET Core .Net Framework
Киев 2017
.Net Core vs .Net Framework
Architecture & Development of .NET Core Applications
Architecture / App Type Linux containers Windows Containers
Microservices on containers .NET Core .NET Core
Monolithic app .NET Core .NET Framework,
.NET Core
Best-in-class performance and scalability .NET Core .NET Core
Windows Server legacy app (“brown-field”)
migration to containers
-- .NET Framework
New container-based development (“green-field”) .NET Core .NET Core
ASP.NET Core .NET Core .NET Core (recommended)
.NET Framework
ASP.NET 4 (MVC 5, Web API 2, and Web Forms) -- .NET Framework
SignalR services .NET Core .NET Framework
.NET Core
WCF, WF, and other legacy frameworks Limited WCF
support in .NET
Core
.NET Framework
Limited WCF support in
.NET Core
Consumption of Azure services .NET Core .NET Framework,
.NET Core
Киев 2017Architecture & Development of .NET Core Applications
Киев 2017
Microservices :: Pros and Cons
• Each microservice is relatively
small—easy to manage and evolve.
• It is possible to scale out individual
areas of the application.
• You can divide the development
work between multiple teams.
• Issues are more isolated.
• You can use the latest technologies.
Architecture & Development of .NET Core Applications
• Distributed application adds
complexity for developers.
• Deployment complexity.
• Atomic transactions usually are
not possible.
• Usually increase hardware
resource needs.
• Communication complexity.
• Correct system decomposition
complexity.
Benefits Disadvantages
Киев 2017
.Net Core Apps :: Hosting
Architecture & Development of .NET Core Applications
Feature App
Service
Service
Fabric
Virtual
Machine
Near-Instant Deployment X X
Scale up to larger machines without redeploy X X
Instances share content and configuration; no need to
redeploy or reconfigure when scaling
X X
Multiple deployment environments (production, staging) X X
Automatic OS update management X
Seamless switching between 32/64 bit platforms X
Deploy code with Git, FTP X X
Deploy code with WebDeploy X X
Deploy code with TFS X X X
Host web or web service tier of multi-tier architecture X X X
Access Azure services like Service Bus, Storage, SQL
Database
X X X
Install any custom MSI X X
Киев 2017
High-Level Architecture
Architecture & Development of .NET Core Applications
User Interface
Business Logic
Data Access
Киев 2017
High-Level Architecture
Architecture & Development of .NET Core Applications
Киев 2017
Architectural Principles
Architecture & Development of .NET Core Applications
• SOLID
• Separation of Concerns
• Explicit Dependencies
• Don’t Repeat Yourself
• Persistence Ignorance
• Bounded Contexts
• Command and Query Responsibility Segregation (CQRS)
• Domain-Driven Design
Киев 2017Architecture & Development of .NET Core Applications
Киев 2017
API :: Direct Communication
Architecture & Development of .NET Core Applications
Back-End
Microservice 1
Microservice 2
Microservice N
…
Client Apps
Киев 2017
API :: API Gateway
Architecture & Development of .NET Core Applications
Back-End
Microservice 1
Microservice 2
Microservice N
…
Client Apps
API Gateway
Киев 2017
API :: Azure API Management
Architecture & Development of .NET Core Applications
Back-End
Microservice 1
Microservice 2
Microservice N
…
Client Apps
Azure API
Management
Киев 2017
API :: Swagger
• Automatically generates API documentation
• Supports Client API generation and discoverability
• Provides ability to automatically consume and integrate
APIs
Architecture & Development of .NET Core Applications
Киев 2017
API :: Swagger Configuration
Architecture & Development of .NET Core Applications
public void ConfigureServices(IServiceCollection services)
{
// API documentation configuration
var swaggerConfigurationInfo = new SwaggerConfigurationInfo() {
Title = “My Application User API ",
Description = "Service provides all user specific information and management api.",
TermsOfService = “None”,
SecuritySchemas = new List<SecurityScheme> {
// Define the OAuth2.0 scheme (i.e. Implicit Flow), for access_token the user of
// Swagger will be redirected to Auth0 Login hosted page to input credentials
new OAuth2Scheme { Type = "oauth2",
Flow = "implicit",
AuthorizationUrl =
m_identityProviderSettings.Auth0Authorize.AbsoluteUri,
Scopes = new Dictionary<string, string>
{ { "openid profile email", "Security API" }}
}}};
// Add Framework API services(API versioning, swagger, etc.)
services.AddApiServices(swaggerConfigurationInfo);
}
Киев 2017
API :: AutoRest
Architecture & Development of .NET Core Applications
{autorest-location}autorest -Input http://{webapiname}.azurewebsites.net/swagger/
public async void InvokeTest()
{
UserApiClient client = new UserApiClient(...);
await client.IdentityUserActivatePostAsync(
new ActivateUserModel
{
ExternalReferenceId = "1354687252",
Password = "Qwerty123"
});
}
Киев 2017
API :: Versioning
Architecture & Development of .NET Core Applications
Back-End
V 1.0
API Gateway
V N.M
…
New Client Apps
Old Client Apps
Киев 2017
API Versioning :: Business Rules
• API versioning shall be applicable for any API endpoint.
• Old versions has to be supported as long as you agreed
with our clients.
• Old API versions should work the same way they worked
before new version was introduced.
• Old APIs shall be marked as deprecated.
• All versions has to be testable via unit/integration tests.
• Best practice is to apply versioning to external API only.
Architecture & Development of .NET Core Applications
Киев 2017
API Versioning :: Versioning in URI
Architecture & Development of .NET Core Applications
• URI Path
https://mywebportal.com/api/v2/getUsers
• Query String
https://mywebportal.com/api/getUsers?v=2.0
Киев 2017
Versioning with Headers
Architecture & Development of .NET Core Applications
GET /api/camps HTTP/1.1
Host: localhost:43333
Content-Type: application/json
X-version: 2.0
GET /api/camps HTTP/1.1
Host: localhost:43333
Content-Type: application/json
Accept: application/json;version=2.0
Киев 2017
Versioning with Content Type
Architecture & Development of .NET Core Applications
GET /api/camps HTTP/1.1
Host: localhost:43333
Content-Type: application/vnd.myapplication.v1+json
Accept: application/vnd.myapplication.v1+json
Киев 2017
Versioning in Action
Architecture & Development of .NET Core Applications
• Use Microsoft ASP.NET API Versioning NuGet package
• Each controller should be marked with API version:
• Old versions of API controllers should be marked as
deprecated:
• Each API version should be stored in Version folder
• Each controller should be placed in specific namespace
• Unit and integration tests should be also stored separately
Киев 2017Architecture & Development of .NET Core Applications
Киев 2017
EF Core :: Resilient Connections
Architecture & Development of .NET Core Applications
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DbContext>(options =>
{
options.UseSqlServer(Configuration["ConnectionString"],
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.EnableRetryOnFailure(
maxRetryCount: 5,
maxRetryDelay: TimeSpan.FromSeconds(10),
errorNumbersToAdd: null);
});
});
}
Киев 2017
Resiliency and Transactions
Architecture & Development of .NET Core Applications
System.InvalidOperationException: The configured execution strategy
'SqlServerRetryingExecutionStrategy' does not support user initiated
transactions. Use the execution strategy returned by
'DbContext.Database.CreateExecutionStrategy()' to execute all the operations
in the transaction as a retriable unit.
// Use of resiliency strategy within an explicit transaction
var strategy = dbContext.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async () => {
using (var transaction = dbContext.Database.BeginTransaction()) {
dbContext.Users.Update(user);
await dbContext.SaveChangesAsync();
await eventLogService.SaveEventAsync(userChangedEvent);
transaction.Commit();
}
});
SOLUTION
Киев 2017
EF Core :: Seeding
Architecture & Development of .NET Core Applications
public class Startup
{
// Other Startup code...
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
// Other Configure code...
// Seed data through our custom class
DatabaseSeed.SeedAsync(app).Wait();
// Other Configure code...
}
}
Киев 2017
EF Core :: Seeding
Architecture & Development of .NET Core Applications
public class DatabaseSeed
{
public static async Task SeedAsync(IApplicationBuilder applicationBuilder)
{
var context = (AppDbContext)applicationBuilder.
ApplicationServices.GetService(typeof(AppDbContext));
using (context)
{
context.Database.Migrate();
if (!context.Users.Any())
{
context.Users.AddRange(...);
await context.SaveChangesAsync();
}
if (!context.Departments.Any())
{
context.Departments.AddRange(...);
await context.SaveChangesAsync();
}
}
}
}
Киев 2017
EF Core :: Seeding Improvement
Architecture & Development of .NET Core Applications
• Use standard migration mechanism.
• Create base class(es) for seed migrations.
• Specify data context via attribute.
Киев 2017
EF Core :: Seeding Improvement
Architecture & Development of .NET Core Applications
/// <summary>
/// Seed Roles, RolesClaims and UserRoles
/// </summary>
[DbContext(typeof(MyContext))]
[Migration("SEED_201709121256_AddRolesClaimsUserRoles")]
public class AddRolesClaimsUserRoles : EmptyDbSeedMigration
{
/// <summary>
/// <see cref="SeedMigrationBase.PopulateData"/>
/// </summary>
protected override void PopulateData()
{
...
}
}
Киев 2017
EF Core :: InMemory Databases
Architecture & Development of .NET Core Applications
public class Startup
{
// Other Startup code ...
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfiguration>(Configuration);
// DbContext using an InMemory database provider
services.AddDbContext<AppDbContext>(opt =>
opt.UseInMemoryDatabase());
}
// Other Startup code ...
}
Киев 2017Architecture & Development of .NET Core Applications
Киев 2017
.NET Core Apps :: Health Cheks
Architecture & Development of .NET Core Applications
• https://github.com/aspnet/HealthChecks
• src/common
• src/Microsoft.AspNetCore.HealthChecks
• src/Microsoft.Extensions.HealthChecks
• src/Microsoft.Extensions.HealthChecks.SqlServer
• src/Microsoft.Extensions.HealthChecks.AzureStorage
Киев 2017
.NET Core Apps :: Health Checks
Architecture & Development of .NET Core Applications
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseHealthChecks("/hc)
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
Киев 2017
.NET Core Apps :: Health Checks
Architecture & Development of .NET Core Applications
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Add health checks here.
services.AddHealthChecks(checks => {
checks.AddUrlCheck(“URL Check" )
.AddHealthCheckGroup("servers",
group => group
.AddUrlCheck("https://myserviceurl::8010")
.AddUrlCheck("https://tmysecondserviceurl:7777"))
}
services.AddMvc();
}
}
Киев 2017
.NET Core Apps :: Health Checks
Architecture & Development of .NET Core Applications
checks.AddSqlCheck("MyDatabase", Configuration["ConnectionString"]);
checks.AddAzureBlobStorageCheck("accountName", "accountKey");
checks.AddAzureBlobStorageCheck("accountName", "accountKey", "containerName");
checks.AddAzureTableStorageCheck("accountName", "accountKey");
checks.AddAzureTableStorageCheck("accountName", "accountKey", "tableName");
checks.AddAzureFileStorageCheck("accountName", "accountKey");
checks.AddAzureFileStorageCheck("accountName", "accountKey", "shareName");
checks.AddAzureQueueStorageCheck("accountName", "accountKey");
checks.AddAzureQueueStorageCheck("accountName", "accountKey", "queueName");
Киев 2017
.NET Core Apps :: Health Checks
Architecture & Development of .NET Core Applications
checks.AddHealthCheckGroup("memory",
group => group.AddPrivateMemorySizeCheck(1)
.AddVirtualMemorySizeCheck(2)
.AddWorkingSetCheck(1), CheckStatus.Unhealthy)
.AddCheck("thrower", Func<IHealthCheckResult>)
(() => { throw new DivideByZeroException(); }))
.AddCheck("long-running", async cancellationToken => {
await Task.Delay(10000, cancellationToken);
return HealthCheckResult.Healthy("I ran too long"); })
.AddCheck<CustomHealthCheck>("custom");
Киев 2017
Service Fabric Health Monitoring
Architecture & Development of .NET Core Applications
fabric:/System
Киев 2017
Service Fabric Health Hierarchy
Architecture & Development of .NET Core Applications
Cluster
Nodes Applications
Deployed
Applications
Deployed Service
Packages
Services
Partitions
Replicas
Киев 2017
Cluster Health Policy
Architecture & Development of .NET Core Applications
<FabricSettings>
<Section Name="HealthManager/ClusterHealthPolicy">
<Parameter Name="ConsiderWarningAsError" Value="False" />
<Parameter Name="MaxPercentUnhealthyApplications" Value=“10" />
<Parameter Name="MaxPercentUnhealthyNodes" Value=“10" />
<Parameter Name="ApplicationTypeMaxPercentUnhealthyApplications-
YourApplicationType" Value="0" />
</Section>
</FabricSettings>
• Consider Warning as Error
• Max Percent Unhealthy Applications
• Max percent Unhealthy Nodes
• Application Type Health Policy Map
Киев 2017
Service Fabric :: Health Reports
Architecture & Development of .NET Core Applications
private static Uri ApplicationName = new Uri("fabric:/MyApplication");
private static string ServiceManifestName = “MyApplication.Service";
private static string NodeName = FabricRuntime.GetNodeContext().NodeName;
private static Timer ReportTimer = new Timer(new TimerCallback(SendReport), null, 3000, 3000);
private static FabricClient Client = new FabricClient(new FabricClientSettings() {
HealthOperationTimeout = TimeSpan.FromSeconds(120),
HealthReportSendInterval = TimeSpan.FromSeconds(0),
HealthReportRetrySendInterval = TimeSpan.FromSeconds(40)});
public static void SendReport(object obj) {
// Test whether the resource can be accessed from the node
HealthState healthState = TestConnectivityToExternalResource();
var deployedServicePackageHealthReport = new DeployedServicePackageHealthReport(
ApplicationName, ServiceManifestName, NodeName,
new HealthInformation("ExternalSourceWatcher", "Connectivity", healthState));
Client.HealthManager.ReportHealth(deployedServicePackageHealthReport);
}
Киев 2017
Service Fabric + App Insights
Architecture & Development of .NET Core Applications
https://github.com/DeHeerSoftware/Azure-Service-Fabric-Logging-And-Monitoring
Serilog.Sinks.ApplicationInsights
Киев 2017Architecture & Development of .NET Core Applications
Thank you!

More Related Content

What's hot (20)

PPT
.NET Core Apps: Design & Development
GlobalLogic Ukraine
 
PDF
MongoDB World 2019: Building Flexible and Secure Customer Applications with M...
MongoDB
 
PDF
MongoDB Launchpad 2016: Moving Cybersecurity to the Cloud
MongoDB
 
PPTX
Micro services Architecture
Jenis Dharmadurai
 
PDF
Building microservices web application using scala & akka
Binh Nguyen
 
PDF
Digital Forensics and Incident Response in The Cloud Part 3
Velocidex Enterprises
 
PDF
MongoDB .local London 2019: New Encryption Capabilities in MongoDB 4.2: A Dee...
MongoDB
 
PDF
MongoDB .local London 2019: Modern Data Backup and Recovery from On-premises ...
MongoDB
 
PPTX
.Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20...
Javier García Magna
 
ODP
Istio
Arun prasath
 
PDF
What Does Kubernetes Look Like?: Performance Monitoring & Visualization with ...
InfluxData
 
PDF
Monitoring Big Data Systems Done "The Simple Way" - Demi Ben-Ari - Codemotion...
Codemotion
 
PDF
IoT 'Megaservices' - High Throughput Microservices with Akka
Lightbend
 
PDF
Jax london - Battle-tested event-driven patterns for your microservices archi...
Natan Silnitsky
 
PPTX
Cloud native policy enforcement with Open Policy Agent
LibbySchulze
 
PDF
Service Discovery 101
Stefan Achtsnit
 
PPTX
Data stores: beyond relational databases
Javier García Magna
 
PPTX
Market Trends in Microsoft Azure
GlobalLogic Ukraine
 
PPTX
NGINX, Istio, and the Move to Microservices and Service Mesh
NGINX, Inc.
 
PPTX
Communication Amongst Microservices: Kubernetes, Istio, and Spring Cloud - An...
VMware Tanzu
 
.NET Core Apps: Design & Development
GlobalLogic Ukraine
 
MongoDB World 2019: Building Flexible and Secure Customer Applications with M...
MongoDB
 
MongoDB Launchpad 2016: Moving Cybersecurity to the Cloud
MongoDB
 
Micro services Architecture
Jenis Dharmadurai
 
Building microservices web application using scala & akka
Binh Nguyen
 
Digital Forensics and Incident Response in The Cloud Part 3
Velocidex Enterprises
 
MongoDB .local London 2019: New Encryption Capabilities in MongoDB 4.2: A Dee...
MongoDB
 
MongoDB .local London 2019: Modern Data Backup and Recovery from On-premises ...
MongoDB
 
.Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20...
Javier García Magna
 
Istio
Arun prasath
 
What Does Kubernetes Look Like?: Performance Monitoring & Visualization with ...
InfluxData
 
Monitoring Big Data Systems Done "The Simple Way" - Demi Ben-Ari - Codemotion...
Codemotion
 
IoT 'Megaservices' - High Throughput Microservices with Akka
Lightbend
 
Jax london - Battle-tested event-driven patterns for your microservices archi...
Natan Silnitsky
 
Cloud native policy enforcement with Open Policy Agent
LibbySchulze
 
Service Discovery 101
Stefan Achtsnit
 
Data stores: beyond relational databases
Javier García Magna
 
Market Trends in Microsoft Azure
GlobalLogic Ukraine
 
NGINX, Istio, and the Move to Microservices and Service Mesh
NGINX, Inc.
 
Communication Amongst Microservices: Kubernetes, Istio, and Spring Cloud - An...
VMware Tanzu
 

Similar to .NET Fest 2017. Андрей Антиликаторов. Проектирование и разработка приложений на .NET Core (20)

PDF
Asp. net core 3.0 build modern web and cloud applications (top 13 features +...
Katy Slemon
 
PDF
Built Cross-Platform Application with .NET Core Development.pdf
I-Verve Inc
 
PPTX
Quick Interview Preparation Dot Net Core
Karmanjay Verma
 
PPTX
Getting started with dotnet core Web APIs
Knoldus Inc.
 
DOCX
All the amazing features of asp.net core
GrayCell Technologies
 
PPTX
ASP.NET Core 1.0
Ido Flatow
 
PPTX
O futuro do .NET : O que eu preciso saber
Danilo Bordini
 
PDF
Asp.net Web Development.pdf
Abanti Aazmin
 
PDF
Building the Future: Emerging Practices in .NET Software Development
Damco Solutions
 
PDF
.NET Study Group - ASP.NET Core with GCP
Chen-Tien Tsai
 
PPTX
“ASP.NET Core. Features and architecture”
HYS Enterprise
 
PPTX
Steeltoe and the Open Source .NET Renaissance
VMware Tanzu
 
PDF
Introduction to ASP.NET Core
Avanade Nederland
 
PPTX
.NET Core: a new .NET Platform
Alex Thissen
 
PPTX
Developing Cross-Platform Web Apps with ASP.NET Core1.0
EastBanc Tachnologies
 
PDF
AWS Innovate: Moving Microsoft .Net applications one container at a time - Da...
Amazon Web Services Korea
 
PPTX
.Net platform .Net core fundamentals
Hosein Mansouri
 
PDF
GCPUG.TW Meetup #25 - ASP.NET Core with GCP
Chen-Tien Tsai
 
PPTX
.NET Innovations and Improvements
Jeff Chu
 
PPTX
Container Orchestration for .NET Developers
Mike Melusky
 
Asp. net core 3.0 build modern web and cloud applications (top 13 features +...
Katy Slemon
 
Built Cross-Platform Application with .NET Core Development.pdf
I-Verve Inc
 
Quick Interview Preparation Dot Net Core
Karmanjay Verma
 
Getting started with dotnet core Web APIs
Knoldus Inc.
 
All the amazing features of asp.net core
GrayCell Technologies
 
ASP.NET Core 1.0
Ido Flatow
 
O futuro do .NET : O que eu preciso saber
Danilo Bordini
 
Asp.net Web Development.pdf
Abanti Aazmin
 
Building the Future: Emerging Practices in .NET Software Development
Damco Solutions
 
.NET Study Group - ASP.NET Core with GCP
Chen-Tien Tsai
 
“ASP.NET Core. Features and architecture”
HYS Enterprise
 
Steeltoe and the Open Source .NET Renaissance
VMware Tanzu
 
Introduction to ASP.NET Core
Avanade Nederland
 
.NET Core: a new .NET Platform
Alex Thissen
 
Developing Cross-Platform Web Apps with ASP.NET Core1.0
EastBanc Tachnologies
 
AWS Innovate: Moving Microsoft .Net applications one container at a time - Da...
Amazon Web Services Korea
 
.Net platform .Net core fundamentals
Hosein Mansouri
 
GCPUG.TW Meetup #25 - ASP.NET Core with GCP
Chen-Tien Tsai
 
.NET Innovations and Improvements
Jeff Chu
 
Container Orchestration for .NET Developers
Mike Melusky
 
Ad

More from NETFest (20)

PDF
.NET Fest 2019. Николай Балакин. Микрооптимизации в мире .NET
NETFest
 
PPTX
.NET Fest 2019. Сергей Калинец. Efficient Microservice Communication with .NE...
NETFest
 
PPTX
.NET Fest 2019. Оля Гавриш. .NET Core 3.0 и будущее .NET
NETFest
 
PPTX
.NET Fest 2019. Оля Гавриш. Машинное обучение для .NET программистов
NETFest
 
PPTX
.NET Fest 2019. Roberto Freato. Provisioning Azure PaaS fluently with Managem...
NETFest
 
PPTX
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
NETFest
 
PPTX
.NET Fest 2019. Сергій Бута. Feature Toggles: Dynamic Configuration at Wirex
NETFest
 
PPTX
.NET Fest 2019. Michael Staib. Hot Chocolate: GraphQL Schema Stitching with A...
NETFest
 
PPTX
.NET Fest 2019. Андрей Литвинов. Async lifetime tests with xUnit and AutoFixture
NETFest
 
PPTX
.NET Fest 2019. Анатолий Колесник. Love, Death & F# Tests
NETFest
 
PPTX
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...
NETFest
 
PPTX
.NET Fest 2019. Roberto Freato. Azure App Service deep dive
NETFest
 
PPTX
.NET Fest 2019. Леонид Молотиевский. DotNet Core in production
NETFest
 
PPTX
.NET Fest 2019. Александр Демчук. How to measure relationships within the Com...
NETFest
 
PDF
.NET Fest 2019. Anna Melashkina та Philipp Bauknecht. Dragons in a Mixed Real...
NETFest
 
PDF
.NET Fest 2019. Alex Thissen. Architecting .NET solutions in a Docker ecosystem
NETFest
 
PPTX
.NET Fest 2019. Stas Lebedenko. Practical serverless use cases in Azure with ...
NETFest
 
PPTX
.NET Fest 2019. Сергей Медведев. How serverless makes Integration TDD a reali...
NETFest
 
PPTX
.NET Fest 2019. Сергей Корж. Natural Language Processing in .NET
NETFest
 
PDF
.NET Fest 2019. Eran Stiller. Create Your Own Serverless PKI with .NET & Azur...
NETFest
 
.NET Fest 2019. Николай Балакин. Микрооптимизации в мире .NET
NETFest
 
.NET Fest 2019. Сергей Калинец. Efficient Microservice Communication with .NE...
NETFest
 
.NET Fest 2019. Оля Гавриш. .NET Core 3.0 и будущее .NET
NETFest
 
.NET Fest 2019. Оля Гавриш. Машинное обучение для .NET программистов
NETFest
 
.NET Fest 2019. Roberto Freato. Provisioning Azure PaaS fluently with Managem...
NETFest
 
.NET Fest 2019. Halil Ibrahim Kalkan. Implementing Domain Driven Design
NETFest
 
.NET Fest 2019. Сергій Бута. Feature Toggles: Dynamic Configuration at Wirex
NETFest
 
.NET Fest 2019. Michael Staib. Hot Chocolate: GraphQL Schema Stitching with A...
NETFest
 
.NET Fest 2019. Андрей Литвинов. Async lifetime tests with xUnit and AutoFixture
NETFest
 
.NET Fest 2019. Анатолий Колесник. Love, Death & F# Tests
NETFest
 
.NET Fest 2019. Алексей Голуб. Монадные парсер-комбинаторы в C# (простой спос...
NETFest
 
.NET Fest 2019. Roberto Freato. Azure App Service deep dive
NETFest
 
.NET Fest 2019. Леонид Молотиевский. DotNet Core in production
NETFest
 
.NET Fest 2019. Александр Демчук. How to measure relationships within the Com...
NETFest
 
.NET Fest 2019. Anna Melashkina та Philipp Bauknecht. Dragons in a Mixed Real...
NETFest
 
.NET Fest 2019. Alex Thissen. Architecting .NET solutions in a Docker ecosystem
NETFest
 
.NET Fest 2019. Stas Lebedenko. Practical serverless use cases in Azure with ...
NETFest
 
.NET Fest 2019. Сергей Медведев. How serverless makes Integration TDD a reali...
NETFest
 
.NET Fest 2019. Сергей Корж. Natural Language Processing in .NET
NETFest
 
.NET Fest 2019. Eran Stiller. Create Your Own Serverless PKI with .NET & Azur...
NETFest
 
Ad

Recently uploaded (20)

PDF
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
PDF
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
PPTX
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
PDF
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
PPTX
ENGlish 8 lesson presentation PowerPoint.pptx
marawehsvinetshe
 
PPTX
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
PPTX
Controller Request and Response in Odoo18
Celine George
 
PDF
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
PPTX
Light Reflection and Refraction- Activities - Class X Science
SONU ACADEMY
 
PDF
Council of Chalcedon Re-Examined
Smiling Lungs
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PPTX
Introduction to Indian Writing in English
Trushali Dodiya
 
PPT
Indian Contract Act 1872, Business Law #MBA #BBA #BCOM
priyasinghy107
 
PPTX
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
ENGlish 8 lesson presentation PowerPoint.pptx
marawehsvinetshe
 
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
Controller Request and Response in Odoo18
Celine George
 
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
Light Reflection and Refraction- Activities - Class X Science
SONU ACADEMY
 
Council of Chalcedon Re-Examined
Smiling Lungs
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
Introduction to Indian Writing in English
Trushali Dodiya
 
Indian Contract Act 1872, Business Law #MBA #BBA #BCOM
priyasinghy107
 
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 

.NET Fest 2017. Андрей Антиликаторов. Проектирование и разработка приложений на .NET Core

  • 1. Киев 2017 Только реальные кейсы. Только актуальные тренды. Architecture & Development of .NET Core Applications Andrey Antilikatorov
  • 2. Киев 2017Architecture & Development of .NET Core Applications
  • 3. Киев 2017Architecture & Development of .NET Core Applications
  • 4. Киев 2017 Analytics says… .NET Core will be as popular as Ruby and NodeJS. .NET Core and NodeJS will be the most popular platforms for back-end solution compete on the market. In few years .NET Core (not Java) will be number one choice for enterprise-level applications. Architecture & Development of .NET Core Applications .Net Core, Java, NodeJS…
  • 5. Киев 2017Architecture & Development of .NET Core Applications
  • 6. Киев 2017 .NET Core :: Few Things • Many mechanisms such as authentication, security, component interactions now changed comparing to .Net Framework. • Many components and platforms (for example for Desktop applications) are missing. • Nevertheless, .NET Core provides corporate-level software benefits for small projects. Architecture & Development of .NET Core Applications
  • 7. Киев 2017 .Net Core vs .Net Framework • There are cross-platform needs. • Application architecture is based on microservices. • Scalability and high performance are the must. Need to get as much as possible out of the box. • Need to use both Linux and Windows containers. • You are running multiple .NET versions side-by-side. • Opensource framework is required. Architecture & Development of .NET Core Applications • Application currently uses .NET Framework and has strong dependencies on Windows. • Need to use Windows APIs that are not supported by .NET Core. • Need to use third-party libraries or NuGet packages that are not available for .NET Core. • Need tools, technologies or platforms not supported by .NET Core. .NET Core .Net Framework
  • 8. Киев 2017 .Net Core vs .Net Framework Architecture & Development of .NET Core Applications Architecture / App Type Linux containers Windows Containers Microservices on containers .NET Core .NET Core Monolithic app .NET Core .NET Framework, .NET Core Best-in-class performance and scalability .NET Core .NET Core Windows Server legacy app (“brown-field”) migration to containers -- .NET Framework New container-based development (“green-field”) .NET Core .NET Core ASP.NET Core .NET Core .NET Core (recommended) .NET Framework ASP.NET 4 (MVC 5, Web API 2, and Web Forms) -- .NET Framework SignalR services .NET Core .NET Framework .NET Core WCF, WF, and other legacy frameworks Limited WCF support in .NET Core .NET Framework Limited WCF support in .NET Core Consumption of Azure services .NET Core .NET Framework, .NET Core
  • 9. Киев 2017Architecture & Development of .NET Core Applications
  • 10. Киев 2017 Microservices :: Pros and Cons • Each microservice is relatively small—easy to manage and evolve. • It is possible to scale out individual areas of the application. • You can divide the development work between multiple teams. • Issues are more isolated. • You can use the latest technologies. Architecture & Development of .NET Core Applications • Distributed application adds complexity for developers. • Deployment complexity. • Atomic transactions usually are not possible. • Usually increase hardware resource needs. • Communication complexity. • Correct system decomposition complexity. Benefits Disadvantages
  • 11. Киев 2017 .Net Core Apps :: Hosting Architecture & Development of .NET Core Applications Feature App Service Service Fabric Virtual Machine Near-Instant Deployment X X Scale up to larger machines without redeploy X X Instances share content and configuration; no need to redeploy or reconfigure when scaling X X Multiple deployment environments (production, staging) X X Automatic OS update management X Seamless switching between 32/64 bit platforms X Deploy code with Git, FTP X X Deploy code with WebDeploy X X Deploy code with TFS X X X Host web or web service tier of multi-tier architecture X X X Access Azure services like Service Bus, Storage, SQL Database X X X Install any custom MSI X X
  • 12. Киев 2017 High-Level Architecture Architecture & Development of .NET Core Applications User Interface Business Logic Data Access
  • 13. Киев 2017 High-Level Architecture Architecture & Development of .NET Core Applications
  • 14. Киев 2017 Architectural Principles Architecture & Development of .NET Core Applications • SOLID • Separation of Concerns • Explicit Dependencies • Don’t Repeat Yourself • Persistence Ignorance • Bounded Contexts • Command and Query Responsibility Segregation (CQRS) • Domain-Driven Design
  • 15. Киев 2017Architecture & Development of .NET Core Applications
  • 16. Киев 2017 API :: Direct Communication Architecture & Development of .NET Core Applications Back-End Microservice 1 Microservice 2 Microservice N … Client Apps
  • 17. Киев 2017 API :: API Gateway Architecture & Development of .NET Core Applications Back-End Microservice 1 Microservice 2 Microservice N … Client Apps API Gateway
  • 18. Киев 2017 API :: Azure API Management Architecture & Development of .NET Core Applications Back-End Microservice 1 Microservice 2 Microservice N … Client Apps Azure API Management
  • 19. Киев 2017 API :: Swagger • Automatically generates API documentation • Supports Client API generation and discoverability • Provides ability to automatically consume and integrate APIs Architecture & Development of .NET Core Applications
  • 20. Киев 2017 API :: Swagger Configuration Architecture & Development of .NET Core Applications public void ConfigureServices(IServiceCollection services) { // API documentation configuration var swaggerConfigurationInfo = new SwaggerConfigurationInfo() { Title = “My Application User API ", Description = "Service provides all user specific information and management api.", TermsOfService = “None”, SecuritySchemas = new List<SecurityScheme> { // Define the OAuth2.0 scheme (i.e. Implicit Flow), for access_token the user of // Swagger will be redirected to Auth0 Login hosted page to input credentials new OAuth2Scheme { Type = "oauth2", Flow = "implicit", AuthorizationUrl = m_identityProviderSettings.Auth0Authorize.AbsoluteUri, Scopes = new Dictionary<string, string> { { "openid profile email", "Security API" }} }}}; // Add Framework API services(API versioning, swagger, etc.) services.AddApiServices(swaggerConfigurationInfo); }
  • 21. Киев 2017 API :: AutoRest Architecture & Development of .NET Core Applications {autorest-location}autorest -Input http://{webapiname}.azurewebsites.net/swagger/ public async void InvokeTest() { UserApiClient client = new UserApiClient(...); await client.IdentityUserActivatePostAsync( new ActivateUserModel { ExternalReferenceId = "1354687252", Password = "Qwerty123" }); }
  • 22. Киев 2017 API :: Versioning Architecture & Development of .NET Core Applications Back-End V 1.0 API Gateway V N.M … New Client Apps Old Client Apps
  • 23. Киев 2017 API Versioning :: Business Rules • API versioning shall be applicable for any API endpoint. • Old versions has to be supported as long as you agreed with our clients. • Old API versions should work the same way they worked before new version was introduced. • Old APIs shall be marked as deprecated. • All versions has to be testable via unit/integration tests. • Best practice is to apply versioning to external API only. Architecture & Development of .NET Core Applications
  • 24. Киев 2017 API Versioning :: Versioning in URI Architecture & Development of .NET Core Applications • URI Path https://mywebportal.com/api/v2/getUsers • Query String https://mywebportal.com/api/getUsers?v=2.0
  • 25. Киев 2017 Versioning with Headers Architecture & Development of .NET Core Applications GET /api/camps HTTP/1.1 Host: localhost:43333 Content-Type: application/json X-version: 2.0 GET /api/camps HTTP/1.1 Host: localhost:43333 Content-Type: application/json Accept: application/json;version=2.0
  • 26. Киев 2017 Versioning with Content Type Architecture & Development of .NET Core Applications GET /api/camps HTTP/1.1 Host: localhost:43333 Content-Type: application/vnd.myapplication.v1+json Accept: application/vnd.myapplication.v1+json
  • 27. Киев 2017 Versioning in Action Architecture & Development of .NET Core Applications • Use Microsoft ASP.NET API Versioning NuGet package • Each controller should be marked with API version: • Old versions of API controllers should be marked as deprecated: • Each API version should be stored in Version folder • Each controller should be placed in specific namespace • Unit and integration tests should be also stored separately
  • 28. Киев 2017Architecture & Development of .NET Core Applications
  • 29. Киев 2017 EF Core :: Resilient Connections Architecture & Development of .NET Core Applications public void ConfigureServices(IServiceCollection services) { services.AddDbContext<DbContext>(options => { options.UseSqlServer(Configuration["ConnectionString"], sqlServerOptionsAction: sqlOptions => { sqlOptions.EnableRetryOnFailure( maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(10), errorNumbersToAdd: null); }); }); }
  • 30. Киев 2017 Resiliency and Transactions Architecture & Development of .NET Core Applications System.InvalidOperationException: The configured execution strategy 'SqlServerRetryingExecutionStrategy' does not support user initiated transactions. Use the execution strategy returned by 'DbContext.Database.CreateExecutionStrategy()' to execute all the operations in the transaction as a retriable unit. // Use of resiliency strategy within an explicit transaction var strategy = dbContext.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async () => { using (var transaction = dbContext.Database.BeginTransaction()) { dbContext.Users.Update(user); await dbContext.SaveChangesAsync(); await eventLogService.SaveEventAsync(userChangedEvent); transaction.Commit(); } }); SOLUTION
  • 31. Киев 2017 EF Core :: Seeding Architecture & Development of .NET Core Applications public class Startup { // Other Startup code... public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { // Other Configure code... // Seed data through our custom class DatabaseSeed.SeedAsync(app).Wait(); // Other Configure code... } }
  • 32. Киев 2017 EF Core :: Seeding Architecture & Development of .NET Core Applications public class DatabaseSeed { public static async Task SeedAsync(IApplicationBuilder applicationBuilder) { var context = (AppDbContext)applicationBuilder. ApplicationServices.GetService(typeof(AppDbContext)); using (context) { context.Database.Migrate(); if (!context.Users.Any()) { context.Users.AddRange(...); await context.SaveChangesAsync(); } if (!context.Departments.Any()) { context.Departments.AddRange(...); await context.SaveChangesAsync(); } } } }
  • 33. Киев 2017 EF Core :: Seeding Improvement Architecture & Development of .NET Core Applications • Use standard migration mechanism. • Create base class(es) for seed migrations. • Specify data context via attribute.
  • 34. Киев 2017 EF Core :: Seeding Improvement Architecture & Development of .NET Core Applications /// <summary> /// Seed Roles, RolesClaims and UserRoles /// </summary> [DbContext(typeof(MyContext))] [Migration("SEED_201709121256_AddRolesClaimsUserRoles")] public class AddRolesClaimsUserRoles : EmptyDbSeedMigration { /// <summary> /// <see cref="SeedMigrationBase.PopulateData"/> /// </summary> protected override void PopulateData() { ... } }
  • 35. Киев 2017 EF Core :: InMemory Databases Architecture & Development of .NET Core Applications public class Startup { // Other Startup code ... public void ConfigureServices(IServiceCollection services) { services.AddSingleton<IConfiguration>(Configuration); // DbContext using an InMemory database provider services.AddDbContext<AppDbContext>(opt => opt.UseInMemoryDatabase()); } // Other Startup code ... }
  • 36. Киев 2017Architecture & Development of .NET Core Applications
  • 37. Киев 2017 .NET Core Apps :: Health Cheks Architecture & Development of .NET Core Applications • https://github.com/aspnet/HealthChecks • src/common • src/Microsoft.AspNetCore.HealthChecks • src/Microsoft.Extensions.HealthChecks • src/Microsoft.Extensions.HealthChecks.SqlServer • src/Microsoft.Extensions.HealthChecks.AzureStorage
  • 38. Киев 2017 .NET Core Apps :: Health Checks Architecture & Development of .NET Core Applications public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseHealthChecks("/hc) .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } }
  • 39. Киев 2017 .NET Core Apps :: Health Checks Architecture & Development of .NET Core Applications public class Startup { public void ConfigureServices(IServiceCollection services) { // Add health checks here. services.AddHealthChecks(checks => { checks.AddUrlCheck(“URL Check" ) .AddHealthCheckGroup("servers", group => group .AddUrlCheck("https://myserviceurl::8010") .AddUrlCheck("https://tmysecondserviceurl:7777")) } services.AddMvc(); } }
  • 40. Киев 2017 .NET Core Apps :: Health Checks Architecture & Development of .NET Core Applications checks.AddSqlCheck("MyDatabase", Configuration["ConnectionString"]); checks.AddAzureBlobStorageCheck("accountName", "accountKey"); checks.AddAzureBlobStorageCheck("accountName", "accountKey", "containerName"); checks.AddAzureTableStorageCheck("accountName", "accountKey"); checks.AddAzureTableStorageCheck("accountName", "accountKey", "tableName"); checks.AddAzureFileStorageCheck("accountName", "accountKey"); checks.AddAzureFileStorageCheck("accountName", "accountKey", "shareName"); checks.AddAzureQueueStorageCheck("accountName", "accountKey"); checks.AddAzureQueueStorageCheck("accountName", "accountKey", "queueName");
  • 41. Киев 2017 .NET Core Apps :: Health Checks Architecture & Development of .NET Core Applications checks.AddHealthCheckGroup("memory", group => group.AddPrivateMemorySizeCheck(1) .AddVirtualMemorySizeCheck(2) .AddWorkingSetCheck(1), CheckStatus.Unhealthy) .AddCheck("thrower", Func<IHealthCheckResult>) (() => { throw new DivideByZeroException(); })) .AddCheck("long-running", async cancellationToken => { await Task.Delay(10000, cancellationToken); return HealthCheckResult.Healthy("I ran too long"); }) .AddCheck<CustomHealthCheck>("custom");
  • 42. Киев 2017 Service Fabric Health Monitoring Architecture & Development of .NET Core Applications fabric:/System
  • 43. Киев 2017 Service Fabric Health Hierarchy Architecture & Development of .NET Core Applications Cluster Nodes Applications Deployed Applications Deployed Service Packages Services Partitions Replicas
  • 44. Киев 2017 Cluster Health Policy Architecture & Development of .NET Core Applications <FabricSettings> <Section Name="HealthManager/ClusterHealthPolicy"> <Parameter Name="ConsiderWarningAsError" Value="False" /> <Parameter Name="MaxPercentUnhealthyApplications" Value=“10" /> <Parameter Name="MaxPercentUnhealthyNodes" Value=“10" /> <Parameter Name="ApplicationTypeMaxPercentUnhealthyApplications- YourApplicationType" Value="0" /> </Section> </FabricSettings> • Consider Warning as Error • Max Percent Unhealthy Applications • Max percent Unhealthy Nodes • Application Type Health Policy Map
  • 45. Киев 2017 Service Fabric :: Health Reports Architecture & Development of .NET Core Applications private static Uri ApplicationName = new Uri("fabric:/MyApplication"); private static string ServiceManifestName = “MyApplication.Service"; private static string NodeName = FabricRuntime.GetNodeContext().NodeName; private static Timer ReportTimer = new Timer(new TimerCallback(SendReport), null, 3000, 3000); private static FabricClient Client = new FabricClient(new FabricClientSettings() { HealthOperationTimeout = TimeSpan.FromSeconds(120), HealthReportSendInterval = TimeSpan.FromSeconds(0), HealthReportRetrySendInterval = TimeSpan.FromSeconds(40)}); public static void SendReport(object obj) { // Test whether the resource can be accessed from the node HealthState healthState = TestConnectivityToExternalResource(); var deployedServicePackageHealthReport = new DeployedServicePackageHealthReport( ApplicationName, ServiceManifestName, NodeName, new HealthInformation("ExternalSourceWatcher", "Connectivity", healthState)); Client.HealthManager.ReportHealth(deployedServicePackageHealthReport); }
  • 46. Киев 2017 Service Fabric + App Insights Architecture & Development of .NET Core Applications https://github.com/DeHeerSoftware/Azure-Service-Fabric-Logging-And-Monitoring Serilog.Sinks.ApplicationInsights
  • 47. Киев 2017Architecture & Development of .NET Core Applications Thank you!