Live Traffic Feed

Friday, April 24, 2020

10 Performance-Improvement Tips for ASP.NET Core 3.0 Applications

Leave a Comment
Performance is very important; it is a major factor for the success of any web application. ASP.NET Core 3.0 includes several enhancements that scale back memory usage and improve turnout. In this blog post, I provide 10 tips to help you improve the performance of ASP.NET Core 3.0 applications by doing the following:

Avoid synchronous and use asynchronous

Try to avoid synchronous calling when developing ASP.NET Core 3.0 applications. Synchronous calling blocks the next execution until the current execution is completed. While fetching data from an API or performing operations like I/O operations or independent calling, execute the call in an asynchronous manner.
Avoid using Task.Wait and Task.Result, and try to use await. The following code shows how to do this.
public class WebHost
{
    public virtual async Task StartAsync(CancellationToken cancellationToken = default)
    {
        // Fire IHostedService.Start
        await _hostedServiceExecutor.StartAsync(cancellationToken).ConfigureAwait(false);
        // More setup
        await Server.StartAsync(hostingApp, cancellationToken).ConfigureAwait(false);
        // Fire IApplicationLifetime.Started
        _applicationLifetime?.NotifyStarted();
        // Remaining setup
    }
}
Entity Framework 3.0 Core also provides a set of async extension methods, similar to LINQ methods, that execute a query and return results.

Asynchronous querying

Asynchronous queries avoid blocking a thread while the query is executed in the database. Async queries are important for quick, responsive client applications.
Examples:
  • ToListAsync()
  • ToArrayAsync()
  • SingleAsync()
public async Task<List> GetBlogsAsync()
{
    using (var context = new BloggingContext())
    {
        return await context.Blogs.ToListAsync();
    }
}

Asynchronous saving

Asynchronous saving avoids a thread block while changes are written to the database. It provides DbContext.SaveChangesAsync() as an asynchronous alternative to DbContext.SaveChanges().
public static async Task AddBlogAsync(string url)
{
    using (var context = new BloggingContext())
    {
        var blogContent = new BlogContent { Url = url };
        context.Blogs.Add(blogContent);
        await context.SaveChangesAsync();
    }
}

Optimize data access

Improve the performance of an application by optimizing its data access logic. Most applications are totally dependent on a database. They have to fetch data from the database, process the data, and then display it. If it is time-consuming, then the application will take much more time to load.
Recommendations:
  • Call all data access APIs asynchronously.
  • Don’t try to get data that is not required in advance.
  • Try to use no-tracking queries in Entity Framework Core when accessing data for read-only purposes.
  • Use filter and aggregate LINQ queries (with .Where.Select, or .Sum statements), so filtering can be performed by the database.
You can find approaches that may improve performance of your high-scale apps in the new features of EF Core 3.0.

Use caching technology

Increase the performance of an application by reducing the number of requests to the server. Avoid calling the server every time and cache the data instead. Store the response for the future, and use it the next time you make a call for the same response.
These are some caching techniques:
  • In-memory caching.
  • Distributed cache.
  • Cache tag helper.
  • Distributed cache tag helper.

Use response caching middleware

Middleware controls when responses are cacheable. It stores responses and serves them from the cache. It is available in the Microsoft.AspNetCore.ResponseCaching package, which was implicitly added to ASP.NET Core.
In Startup.ConfigureServices, add the Response Caching Middleware to the service collection.
public void ConfigureServices(IServiceCollection services)
{
    services.AddResponseCaching();
    services.AddRazorPages();
}

Use JSON serialization

ASP.NET Core 3.0 uses System.Text.Json for JSON serialization by default. Now, you can read and write JSON asynchronously. This improves performance better than Newtonsoft.Json. The System.Text.Json namespace provides the following features for processing JSON:
  • High performance.
  • Low allocation.
  • Standards-compliant capabilities.
  • Serializing objects to JSON text and deserializing JSON text to objects.

Reduce HTTP requests

Reducing the number of HTTP requests is one of the major optimizations. Cache the webpages and avoid client-side redirects to reduce the number of connections made to the web server.
Use the following techniques to reduce the HTTP requests:
  1. Use minification.
  2. Use bundling.
  3. Use sprite images.
By reducing HTTP requests, these techniques help pages load faster.

Use exceptions only when necessary

Exceptions should be rare. Throwing and catching exceptions will consume more time relative to other code flow patterns.
  • Don’t throw and catch exceptions in normal program flow.
  • Use exceptions only when they are needed.

Use response compression

Response compression, which compresses the size of a file, is another factor in improving performance. In ASP.NET Core, response compression is available as a middleware component.
Usually, responses are not natively compressed. This typically includes CSS, JavaScript, HTML, XML, and JSON.
  • Don’t compress natively compressed assets, such as PNG files.
  • Don’t compress files smaller than about 150-1000 bytes
(source: https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AspNetCoreGuidance.md
Package: Microsoft.AspNetCore.ResponseCompression is implicitly included in ASP.NET Core apps.
The following sample code shows how to enable Response Compression Middleware for the default MIME types and compression providers.
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddResponseCompression();
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseResponseCompression();
    }
}
These are the providers:
public void ConfigureServices(IServiceCollection services)
{
    services.AddResponseCompression(options =>
    {
        options.Providers.Add<BrotliCompressionProvider>();
        options.Providers.Add<GzipCompressionProvider>();
        options.Providers.Add<CustomCompressionProvider>();
        options.MimeTypes =
            ResponseCompressionDefaults.MimeTypes.Concat(
                new[] { "image/svg+xml" });
    });
}

HttpContext accessibility improvements

HttpContext accessibility is only valid as long as there is an active HTTP request in ASP.NET Core. Here are some suggestions for accessing HttpContext from Microsoft’s documentation:

Client-side improvements

Client-side optimization is one important aspect of improving performance. When creating a website using ASP.Net Core, consider the following tips:

Bundling

Bundling combines multiple files into a single file, reducing the number of server requests. You can use multiple individual bundles in a webpage.

Minification

Minification removes unnecessary characters from code without changing any functionality, also reducing file size. After applying minification, variable names are shortened to one character and comments and unnecessary whitespace are removed.

Loading JavaScript at last

Load JavaScript files at the end. If you do that, static content will show faster, so users won’t have to wait to see the content.

Use a content delivery network

Use a content delivery network (CDN) to load static files such as images, JS, CSS, etc. This keeps your data close to your consumers, serving it from the nearest local server.
Read More

Thursday, April 23, 2020

Best 20 .net core libraries every developer should know

Leave a Comment
Net Core is a lightweight and cross-platform version of the DotNet framework and the wonderful thing is that Developers required the same expertise to code with .Net Core as .Net Framework.
With Every new Update, new features are added that help developers deploy high-performance & highly scalable applications using less Code.
In this article, I’m listing down some of the most useful but not very commonly used .Net Core Libraries that every developer needs to know.

LITEDB

LiteDB is a lightweight, small & fast NoSQL embedded database. It’s Open source & freely available for everyone, also for commercial usage. LiteDB is fast & also support LINQ queries. It stores data in documents & support Datafile encryption using DES (AES).
Like SQLite, LiteDB also stores data in a single file. It can also index document fields for fast search.

CACHEMANAGER

CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features.
CacheManager makes developer’s life simpler by handling very complex cache scenarios. It also provides the implementation of multiple layers of caching in just a few lines of code, e.g. in-process caching in front of a distributed cache.

SMIDGE

A lightweight runtime CSS/JavaScript file minification, combination, compression & management library for ASP.Net Core. It supports compression, Minification & combination for CSS/JS Files. It properly configures client-side caching & persistent server-side caching.
Smidge is easily extensible. You can completely customize the pre-processor pipeline and create your own processors for any file type.

BCRYPT.NET-CORE

A .net Core version of BCrypt.net, with enhanced features and security. Compatible with .net framework as well as .net core. It should be a drop-in replacement for BCrypt.net as the namespaces are unchanged.

ASPNETCORE.DIAGNOSTICS.HEALTHCHECKS

This project is a BeatPulse liveness and UI port to new Microsoft Health Checks feature included on ASP.NET Core 2.2. It supports almost every commonly used database including MySql, Sql Server, Sqlite, MongoDB, Amazon S3, Postgres, Elasticsearch, DynamoDb & many other.

FLUENTEMAIL

Send email from .NET or .NET Core. Many useful extension packages make this very simple and powerful. It also offers Email body as a template. We can also use a template from disk. Here’s the basic usage example, look how simple it is.
  1. var email = Email
  2. .From("john@email.com")
  3. .To("bob@email.com", "bob")
  4. .Subject("hows it going bob")
  5. .Body("yo dawg, sup?")
  6. .Send();

UNITCONVERSION

UnitConversion is designed to be expansible through factories or through concrete converter implementations. It supports Mass Conversion, Time Conversion, Area Conversion, Distance Conversion & Volume Conversion.

FASTREPORT

FastReport provides open source report generator for .NET Core 2.x/.Net Framework 4.x. You can use the FastReport in MVC, Web API applications.
You can get data from XML, JSON, CSV, MySql, MSSQL, Oracle, Postgres, SQLite, MongoDB, Couchbase, RavenDB.

AUTOCOMPLETE

A very simple, Persistent, powerful and portable autocomplete library. Ready for desktop, web & cloud. It Supports all stream types, including on classical disc storage for cheapest hosting. Considered as one of the fastest autocomplete algorithms with O(n) complexity for searching.

APPMETRICS

App Metrics is an open-source and cross-platform library used to record metrics within an application. it provides several metric types to measure things such as the count of login users over time, the rate of requests, measure time to run a DB query, measure the amount of free memory and so on. It supports Counters, Meters, Gauges, Histograms and Timers etc.

SHARPCOMPRESS

SharpCompress is a compression library that can unzip, unrar, un7zip, untar unbzip2 and ungzip with forward-only reading and file random access APIs. Write support for zip/tar/bzip2/gzip are implemented.
The major feature is support for non-seekable streams so large files can be done on the fly.

HASHLIB

Here you can find implementations of many hashing algorithms e.g. all sha3 round 2 and 3 candidates. You can hash files, streams, common types of data.

NOPCOMMERCE

nopCommerce is the best open-source e-commerce shopping cart. nopCommerce is available for free. It is a fully customizable shopping cart. It’s stable and highly usable. nopCommerce is an open source ecommerce solution.
nopCommerce can be up-and-running in just a few clicks. just download and follow the simple instructions. It’s also optimised for search engines & has friendly URLs.

MAILKIT

The main goal of this project is to provide the .NET world with robust, fully featured and RFC-compliant SMTP, POP3, and IMAP client implementations.

CSCORE

A free .NET audio library which is completely written in C#. it offers many features like playing or capturing audio, en- or decoding many different codecs, effects and much more!

NETOFFICE

NetOffice supports extending and automating Microsoft Office applications: Excel, Word, Outlook, PowerPoint, Access, Project and Visio. It doesn’t have any version limitation. It supports Office versions from 2000 to the latest version.

SSH.NET

This project was inspired by Sharp.SSH library which was adopted from java and it seems like was not supported for quite some time. This library is a complete rewrite, without any third party dependencies, using parallelism to achieve the best performance possible.
It provides SSH commands using Sync & Async methods. SFTP functionality also supports Sync & Async operations. Supports two-factor or higher authentication as well.

SIGNALR

ASP.NET SignalR is a library for ASP.NET developers that makes it incredibly simple to add real-time web functionality to your applications.
“real-time web” functionality is the ability to have your server-side code push content to the connected clients as it happens, in real-time.

C-SHARP-ALGORITHMS

A C# plug-and-play class-library project of Algorithms & standard Data Structures. It includes 30+ Algorithms & 35+ Data Structures designed as Object-Oriented separate components. Actually, this project was started for educational purposes, the implemented Algorithms & Data Structures are efficient, standard, tested & stable.

NANCY

Nancy is a lightweight framework for building HTTP based services on .NET Framework/Core and Mono.
Nancy is designed to handle GET, POST, PUT, DELETE, HEAD, OPTIONS, & PATCH requests and provides a simple, elegant way for returning a response with just a couple of keystrokes, leaving you with more time to focus on the important logic of your application.
Read More

ASP.NET Core-Based Open-Source Projects

Leave a Comment
Open-source projects are great for getting started and serve as a good source for architecture reference. There are several open-source ASP.NET Core projects available in GitHub. These projects will help you learn ASP.NET Core technology in-depth, with different types of architecture and coding patterns. Some of the top real-time applications or sample architecture reference projects across different categories are listed in this article.
What are you waiting for? Check out these projects and get started!

nopCommerce

nopCommerce is a popular open-source e-commerce shopping cart application. It is stable and supports several customizations to suit your needs. There are several plugins available to enhance it.
Domain: E-commerce
Type: Real-time application
License: GPLv3 license plus the “powered by nopCommerce” text requirement on each page
Stars: 4.1k

OrchardCore

OrchardCore is an open-source content management system (CMS) framework supporting modularity and multitenancy.
Domain: CMS
Type: Real-time application
License: BSD 3-Clause
Stars: 3.3k

SimplCommerce

SimplCommerce is a modular, microservice-based e-commerce application, built using ASP.NET Core.
Domain: E-commerce
Type: Real-time application
License: Apache 2.0
Stars: 2.4k

squidex

squidex is a headless CMS and content management hub, built using ASP.NET Core with OData and CQRS patterns.
Domain: CMS
Type: Real-time application
License: MIT
Stars: 831

Miniblog.Core

Miniblog.Core is a blog engine based on ASP.NET Core.
Domain: Blog engine
Type: Real-time application
License: Apache 2.0
Stars: 807

piranha.core

piranha.core is a CMS application based on ASP.NET Core.
Domain: CMS
Type: Real-time application
License: MIT
Stars – 642

Blogifier

Blogifier is a lightweight blog engine written in ASP.NET Core.
Domain: Blog engine
Type: Real-time application
License: MIT
Stars: 466

eShopOnContainers

eShopOnContainers is a sample reference application demonstrating various architecture patterns of container-based microservices by Microsoft.
Architecture: Container-based microservices
Type: Reference application
License: MIT
Stars: 11.9k

eShopOnWeb

eShopOnWeb is a sample reference application demonstrating monolithic architecture powered by Microsoft.
Architecture: Monolithic
Type: Reference application
License: MIT
Stars: 3.6k

practical-aspnetcore

practical-aspnetcore is a practical sample for ASP.NET Core.
Type: Samples
License: MIT
Stars: 3.1k

NorthwindTraders

NorthwindTraders is a sample reference application for domain-driven architecture using Entity Framework and CQRS pattern.
Architecture: Clean architecture, DDD, CQRS
Type: Sample reference application
License: MIT
Stars: 2.9k

ReactiveTraderCloud

ReactiveTraderCloud is a real-time trading application demonstrating reactive programming principles.
Architecture: Reactive programming
Type: Sample reference application
License: Apache 2.0
Stars: 1.2k

coolstore-microservices

coolstore-microservices is a sample application demonstrating the use of Kubernetes using a service mesh.
Architecture: Kubernetes-based microservice using service mesh
Type: Sample reference application
License: MIT
Stars: 1.1k

cloudscribe

cloudscribe is a foundation framework for building a multitenant application.
Architecture: Multitenant framework
Type: Sample reference application
License: Apache 2.0
Stars: 829

clean-architecture-manga

clean-architecture-manga is a clean architecture sample application.
Architecture: Clean architecture
Type: Sample reference application
License: Apache
Stars: 852

StarWars

StarWars is a GraphQL-based ASP.NET Core Star Wars application.
Architecture: GraphQL
Type: Sample reference application
License: MIT
Stars: 460

sample-dotnet-core-cqrs-api

sample-dotnet-core-cqrs-api is a sample project demonstrating the use of Rest API clean architecture with the CQRS pattern.
Architecture: Clean architecture, DDD, CQRS
Type: Sample reference application
License: Not specified
Stars: 384

Pos

Pos is a sample project demonstrating the use of microservices.
Architecture: Microservices, DDD, CQRS
Type: Sample reference application
License: Not specified
Stars: 112

Conclusion

Apart from these applications, you can check out some more awesome .NET Core libraries, tools, and frameworks on this GitHub page.
Syncfusion provides 70+ high-performance, lightweight, modular, and responsive ASP.NET Core UI controls such as DataGridCharts, and Scheduler. You can use these controls in your application development.
If you have any questions, please let us know in the comments section. You can also contact us through our Support ForumDirect-Trac, or Feedback Portal. We are happy to assist you!
Read More