SlideShare a Scribd company logo
1
.NET Core Applications: Design &
Development
Andrii Antilikatorov
2
33
4
.Net Core, Java, NodeJS…
.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.
Analytics says…
55
6
.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) missing.
• .NET Core provides corporate-level software
benefits for small projects
Photo is
example for
placement and
max. size
7
.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.
.NET Core
• 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 Framework
8
.Net Core vs .Net Framework :: Docker Containers
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
99
Architecture – General Approach
10
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.
Benefits
• Distributed application adds complexity for
developers.
• Deployment complexity.
• Atomic transactions usually are not possible.
• Usually increase hardware resource needs
• Communication complexity.
• Partitioning the microservices.
Disadvantages
11
.Net Core Apps :: Hosting
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
User InterfaceUser Interface
Business LogicBusiness Logic
Data AccessData Access
High-Level Architecture
13
High-Level Architecture
14
Architectural Principles
• SOLID
• Separation of Concerns
• Explicit Dependencies
• Don’t Repeat Yourself
• Persistence Ignorance
• Bounded Contexts
• Command and Query Responsibility Segregation (CQRS)
• Domain-Driven Design
1515
16
API :: Direct Communication
Back-EndBack-End
Microservice 1
Microservice 2
Microservice N
Client AppsClient Apps
17
API :: API Gateway
Back-EndBack-End
Microservice 1
Microservice 2
Microservice N
Client AppsClient Apps
API Gateway
18
API :: API Gateway with Azure API Management
Back-EndBack-End
Microservice 1
Microservice 2
Microservice N
Client AppsClient Apps
Azure API
Management
19
API :: Swagger
• Automatically generates API documentation
• Supports Client API generation and discoverability
• Provides ability to automatically consume and integrate APIs
20
API :: Swagger :: Configuration
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
API :: AutoRest
{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
API Versioning
Back-EndBack-End
V 1.0
API Gateway
V N.M
New Client AppsNew Client Apps
Old Client AppsOld Client Apps
23
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.
24
API Versioning :: Versioning in the URI
• URI Path
https://mywebportal.com/api/v2/getUsers
• Query String
https://mywebportal.com/api/getUsers?v=2.0
25
API Versioning :: Versioning with Header/Accept Header
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
API Versioning :: Versioning with Content Type
GET /api/camps HTTP/1.1
Host: localhost:43333
Content-Type: application/vnd.myapplication.v1+json
Accept: application/vnd.myapplication.v1+json
27
API Versioning :: Versioning in Action
• Use Microsoft ASP.NET Api Versioning NuGet package
- Each controller should be marked with API version:
- Each old version API controller 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
29
EF Core :: Resilient Connections
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
EF Core :: Resilient Connections and Transactions
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
EF Core :: Seeding
public class Startup
{
// Other Startup code...
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
// Other Configure code...
// Seed data through our custom class
CatalogContextSeed.SeedAsync(app).Wait();
// Other Configure code...
}
}
32
EF Core :: Seeding
public class CatalogContextSeed {
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
EF Core :: Seeding Improvement
• Use standard migration mechanism.
• Create base class(es) for seed migrations.
• Specify data context via attribute.
34
EF Core :: Seeding Improvement
/// <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
EF Core :: In-Memory Database
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 ...
}
3636
37
Health Checks
• 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
Health Checks :: Middleware Registration
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
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();
}
}
Health Checks :: Web Resources
40
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");
Health Checks :: Azure Resources
41
Health Checks :: Custom Resources
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
Health Checks :: Service Fabric Health Monitoring
43
Health Checks :: Service Fabric :: Health Hierarchy
Cluster
Nodes Applications
Deployed
Applications
Deployed Service
Packages
Services
Partitions
Replicas
44
Health Checks :: Service Fabric :: Cluster Health Policy
<FabricSettings>
<Section Name="HealthManager/ClusterHealthPolicy">
<Parameter Name="ConsiderWarningAsError" Value="False" />
<Parameter Name="MaxPercentUnhealthyApplications" Value=“10" />
<Parameter Name="MaxPercentUnhealthyNodes" Value=“10" />
<Parameter Name="ApplicationTypeMaxPercentUnhealthyApplications-
ControlApplicationType" Value="0" />
</Section>
</FabricSettings>
• Consider Warning as Error
• Max Percent Unhealthy Applications
• Max percent Unhealthy Nodes
• Application Type Health Policy Map
45
Health Checks :: Service Fabric :: Health Reports
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
Service Fabric + App Insights
https://github.com/DeHeerSoftware/Azure-Service-Fabric-Logging-And-Monitoring
Serilog.Sinks.ApplicationInsights
4747
Thank you!

More Related Content

What's hot (20)

PPTX
Docker y azure container service
Fernando Mejía
 
PDF
How Microsoft learned to love Java
Brian Benz
 
PPTX
Introduction to Windows Azure Data Services
Robert Greiner
 
PPTX
Extending Windows Admin Center to manage your applications and infrastructure...
Microsoft Tech Community
 
PDF
Windows azure sql_database_security_isug012013
sqlserver.co.il
 
PDF
JavaCro'15 - Service Discovery in OSGi Beyond the JVM using Docker and Consul...
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
PPTX
PASS VC: SQL Server Performance Monitoring and Baselining
PARIKSHIT SAVJANI
 
PPTX
Geek Sync | Taking Your First Steps to the Cloud—Building a Hybrid Model
IDERA Software
 
PPTX
Microservices using .Net core
girish goudar
 
PPTX
Full Stack Development With Node.Js And NoSQL (Nic Raboy & Arun Gupta)
Red Hat Developers
 
PDF
Introducing the WSO2 Developer Studio Tools for SOA Developers
WSO2
 
PDF
DataStax | DSE Production-Certified Cassandra on Pivotal Cloud Foundry (Ben L...
DataStax
 
PPTX
SQL ON Azure (decision-matrix)
PARIKSHIT SAVJANI
 
PPTX
Windows Azure Diagnostics
Neil Mackenzie
 
PPTX
Choosing the right Cloud Database
Janakiram MSV
 
PDF
Highlights of OpenStack Mitaka and the OpenStack Summit
Cloud Standards Customer Council
 
PDF
THEFT-PROOF JAVA EE - SECURING YOUR JAVA EE APPLICATIONS
Markus Eisele
 
PPTX
Azure sql introduction
ManishK55
 
PDF
Introduction to Windows Azure
Ravi Ranjan Karn
 
PPTX
Mysql ecosystem in 2019
Alkin Tezuysal
 
Docker y azure container service
Fernando Mejía
 
How Microsoft learned to love Java
Brian Benz
 
Introduction to Windows Azure Data Services
Robert Greiner
 
Extending Windows Admin Center to manage your applications and infrastructure...
Microsoft Tech Community
 
Windows azure sql_database_security_isug012013
sqlserver.co.il
 
JavaCro'15 - Service Discovery in OSGi Beyond the JVM using Docker and Consul...
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
PASS VC: SQL Server Performance Monitoring and Baselining
PARIKSHIT SAVJANI
 
Geek Sync | Taking Your First Steps to the Cloud—Building a Hybrid Model
IDERA Software
 
Microservices using .Net core
girish goudar
 
Full Stack Development With Node.Js And NoSQL (Nic Raboy & Arun Gupta)
Red Hat Developers
 
Introducing the WSO2 Developer Studio Tools for SOA Developers
WSO2
 
DataStax | DSE Production-Certified Cassandra on Pivotal Cloud Foundry (Ben L...
DataStax
 
SQL ON Azure (decision-matrix)
PARIKSHIT SAVJANI
 
Windows Azure Diagnostics
Neil Mackenzie
 
Choosing the right Cloud Database
Janakiram MSV
 
Highlights of OpenStack Mitaka and the OpenStack Summit
Cloud Standards Customer Council
 
THEFT-PROOF JAVA EE - SECURING YOUR JAVA EE APPLICATIONS
Markus Eisele
 
Azure sql introduction
ManishK55
 
Introduction to Windows Azure
Ravi Ranjan Karn
 
Mysql ecosystem in 2019
Alkin Tezuysal
 

Similar to .NET Core Apps: Design & Development (20)

PPTX
.NET Fest 2017. Андрей Антиликаторов. Проектирование и разработка приложений ...
NETFest
 
PPTX
Getting started with dotnet core Web APIs
Knoldus Inc.
 
PPTX
Quick Interview Preparation Dot Net Core
Karmanjay Verma
 
PDF
Built Cross-Platform Application with .NET Core Development.pdf
I-Verve Inc
 
PDF
Asp. net core 3.0 build modern web and cloud applications (top 13 features +...
Katy Slemon
 
PPTX
Micro services
Brian Perera
 
PDF
Architecting ASP.NET Core Applications Carl-Hugo Marcotte
rddhwsf007
 
PDF
Building the Future: Emerging Practices in .NET Software Development
Damco Solutions
 
PDF
Asp.net Web Development.pdf
Abanti Aazmin
 
DOCX
All the amazing features of asp.net core
GrayCell Technologies
 
PDF
【BS1】What’s new in visual studio 2022 and c# 10
日本マイクロソフト株式会社
 
PPTX
ASP.NET Developer Roadmap 2021
Ronak Sankhala
 
PDF
[PDF Download] Architecting ASP.NET Core Applications Carl-Hugo Marcotte full...
zenzebretti29
 
PDF
Introduction to ASP.NET Core
Avanade Nederland
 
PDF
.NET Application Modernization with PAS and Azure DevOps
VMware Tanzu
 
PPTX
Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher
 
DOCX
Microservices with asp dot net core, a next gen technology
Evincedev
 
PPTX
O futuro do .NET : O que eu preciso saber
Danilo Bordini
 
PPTX
Architecting Microservices in .Net
Richard Banks
 
.NET Fest 2017. Андрей Антиликаторов. Проектирование и разработка приложений ...
NETFest
 
Getting started with dotnet core Web APIs
Knoldus Inc.
 
Quick Interview Preparation Dot Net Core
Karmanjay Verma
 
Built Cross-Platform Application with .NET Core Development.pdf
I-Verve Inc
 
Asp. net core 3.0 build modern web and cloud applications (top 13 features +...
Katy Slemon
 
Micro services
Brian Perera
 
Architecting ASP.NET Core Applications Carl-Hugo Marcotte
rddhwsf007
 
Building the Future: Emerging Practices in .NET Software Development
Damco Solutions
 
Asp.net Web Development.pdf
Abanti Aazmin
 
All the amazing features of asp.net core
GrayCell Technologies
 
【BS1】What’s new in visual studio 2022 and c# 10
日本マイクロソフト株式会社
 
ASP.NET Developer Roadmap 2021
Ronak Sankhala
 
[PDF Download] Architecting ASP.NET Core Applications Carl-Hugo Marcotte full...
zenzebretti29
 
Introduction to ASP.NET Core
Avanade Nederland
 
.NET Application Modernization with PAS and Azure DevOps
VMware Tanzu
 
Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher
 
Microservices with asp dot net core, a next gen technology
Evincedev
 
O futuro do .NET : O que eu preciso saber
Danilo Bordini
 
Architecting Microservices in .Net
Richard Banks
 
Ad

More from GlobalLogic Ukraine (20)

PDF
GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”
GlobalLogic Ukraine
 
PPTX
Deadlocks in SQL - Turning Fear Into Understanding (by Sergii Stets)
GlobalLogic Ukraine
 
PDF
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Ukraine
 
PDF
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Ukraine
 
PDF
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Ukraine
 
PDF
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic Ukraine
 
PPTX
Штучний інтелект як допомога в навчанні, а не замінник.pptx
GlobalLogic Ukraine
 
PPTX
Задачі AI-розробника як застосовується штучний інтелект.pptx
GlobalLogic Ukraine
 
PPTX
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
GlobalLogic Ukraine
 
PDF
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Ukraine
 
PDF
JavaScript Community Webinar #14 "Why Is Git Rebase?"
GlobalLogic Ukraine
 
PDF
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic Ukraine
 
PPTX
Страх і сила помилок - IT Inside від GlobalLogic Education
GlobalLogic Ukraine
 
PDF
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic Ukraine
 
PDF
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic Ukraine
 
PDF
“How to Secure Your Applications With a Keycloak?
GlobalLogic Ukraine
 
PDF
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Ukraine
 
PPTX
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Ukraine
 
PDF
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic Ukraine
 
PDF
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
GlobalLogic Ukraine
 
GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”
GlobalLogic Ukraine
 
Deadlocks in SQL - Turning Fear Into Understanding (by Sergii Stets)
GlobalLogic Ukraine
 
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Ukraine
 
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Ukraine
 
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Ukraine
 
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic Ukraine
 
Штучний інтелект як допомога в навчанні, а не замінник.pptx
GlobalLogic Ukraine
 
Задачі AI-розробника як застосовується штучний інтелект.pptx
GlobalLogic Ukraine
 
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
GlobalLogic Ukraine
 
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Ukraine
 
JavaScript Community Webinar #14 "Why Is Git Rebase?"
GlobalLogic Ukraine
 
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic Ukraine
 
Страх і сила помилок - IT Inside від GlobalLogic Education
GlobalLogic Ukraine
 
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic Ukraine
 
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic Ukraine
 
“How to Secure Your Applications With a Keycloak?
GlobalLogic Ukraine
 
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Ukraine
 
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Ukraine
 
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic Ukraine
 
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
GlobalLogic Ukraine
 
Ad

Recently uploaded (20)

PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
Digital Circuits, important subject in CS
contactparinay1
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 

.NET Core Apps: Design & Development

  • 1. 1 .NET Core Applications: Design & Development Andrii Antilikatorov
  • 2. 2
  • 3. 33
  • 4. 4 .Net Core, Java, NodeJS… .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. Analytics says…
  • 5. 55
  • 6. 6 .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) missing. • .NET Core provides corporate-level software benefits for small projects Photo is example for placement and max. size
  • 7. 7 .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. .NET Core • 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 Framework
  • 8. 8 .Net Core vs .Net Framework :: Docker Containers 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
  • 10. 10 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. Benefits • Distributed application adds complexity for developers. • Deployment complexity. • Atomic transactions usually are not possible. • Usually increase hardware resource needs • Communication complexity. • Partitioning the microservices. Disadvantages
  • 11. 11 .Net Core Apps :: Hosting 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. 12 User InterfaceUser Interface Business LogicBusiness Logic Data AccessData Access High-Level Architecture
  • 14. 14 Architectural Principles • SOLID • Separation of Concerns • Explicit Dependencies • Don’t Repeat Yourself • Persistence Ignorance • Bounded Contexts • Command and Query Responsibility Segregation (CQRS) • Domain-Driven Design
  • 15. 1515
  • 16. 16 API :: Direct Communication Back-EndBack-End Microservice 1 Microservice 2 Microservice N Client AppsClient Apps
  • 17. 17 API :: API Gateway Back-EndBack-End Microservice 1 Microservice 2 Microservice N Client AppsClient Apps API Gateway
  • 18. 18 API :: API Gateway with Azure API Management Back-EndBack-End Microservice 1 Microservice 2 Microservice N Client AppsClient Apps Azure API Management
  • 19. 19 API :: Swagger • Automatically generates API documentation • Supports Client API generation and discoverability • Provides ability to automatically consume and integrate APIs
  • 20. 20 API :: Swagger :: Configuration 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. 21 API :: AutoRest {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. 22 API Versioning Back-EndBack-End V 1.0 API Gateway V N.M New Client AppsNew Client Apps Old Client AppsOld Client Apps
  • 23. 23 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.
  • 24. 24 API Versioning :: Versioning in the URI • URI Path https://mywebportal.com/api/v2/getUsers • Query String https://mywebportal.com/api/getUsers?v=2.0
  • 25. 25 API Versioning :: Versioning with Header/Accept Header 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. 26 API Versioning :: Versioning with Content Type GET /api/camps HTTP/1.1 Host: localhost:43333 Content-Type: application/vnd.myapplication.v1+json Accept: application/vnd.myapplication.v1+json
  • 27. 27 API Versioning :: Versioning in Action • Use Microsoft ASP.NET Api Versioning NuGet package - Each controller should be marked with API version: - Each old version API controller 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. 28
  • 29. 29 EF Core :: Resilient Connections 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. 30 EF Core :: Resilient Connections and Transactions 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. 31 EF Core :: Seeding public class Startup { // Other Startup code... public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { // Other Configure code... // Seed data through our custom class CatalogContextSeed.SeedAsync(app).Wait(); // Other Configure code... } }
  • 32. 32 EF Core :: Seeding public class CatalogContextSeed { 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. 33 EF Core :: Seeding Improvement • Use standard migration mechanism. • Create base class(es) for seed migrations. • Specify data context via attribute.
  • 34. 34 EF Core :: Seeding Improvement /// <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. 35 EF Core :: In-Memory Database 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. 3636
  • 37. 37 Health Checks • 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. 38 Health Checks :: Middleware Registration 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. 39 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(); } } Health Checks :: Web Resources
  • 40. 40 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"); Health Checks :: Azure Resources
  • 41. 41 Health Checks :: Custom Resources 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. 42 Health Checks :: Service Fabric Health Monitoring
  • 43. 43 Health Checks :: Service Fabric :: Health Hierarchy Cluster Nodes Applications Deployed Applications Deployed Service Packages Services Partitions Replicas
  • 44. 44 Health Checks :: Service Fabric :: Cluster Health Policy <FabricSettings> <Section Name="HealthManager/ClusterHealthPolicy"> <Parameter Name="ConsiderWarningAsError" Value="False" /> <Parameter Name="MaxPercentUnhealthyApplications" Value=“10" /> <Parameter Name="MaxPercentUnhealthyNodes" Value=“10" /> <Parameter Name="ApplicationTypeMaxPercentUnhealthyApplications- ControlApplicationType" Value="0" /> </Section> </FabricSettings> • Consider Warning as Error • Max Percent Unhealthy Applications • Max percent Unhealthy Nodes • Application Type Health Policy Map
  • 45. 45 Health Checks :: Service Fabric :: Health Reports 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. 46 Service Fabric + App Insights https://github.com/DeHeerSoftware/Azure-Service-Fabric-Logging-And-Monitoring Serilog.Sinks.ApplicationInsights

Editor's Notes

  • #16: Page 38
  • #23: Page 110
  • #37: Page 38
  • #38: Page 268
  • #39: Page 268
  • #40: Page 268
  • #41: Page 268
  • #42: Page 268
  • #43: https://docs.microsoft.com/en-us/azure/service-fabric/service-fabric-health-introduction
  • #44: https://docs.microsoft.com/en-us/azure/service-fabric/service-fabric-health-introduction
  • #45: https://docs.microsoft.com/en-us/azure/service-fabric/service-fabric-health-introduction
  • #46: https://docs.microsoft.com/en-us/azure/service-fabric/service-fabric-report-health https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/service-fabric/service-fabric-report-health.md
  • #47: https://docs.microsoft.com/en-us/azure/service-fabric/service-fabric-report-health https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/service-fabric/service-fabric-report-health.md