Asp.net core


What is metadata?

Metadata describes every type and member defined in our code in a Multilanguage form. Metadata stores the following information.

  1. Description of assembly.
  2. Identity (name, version, culture, public key).
  3. The types that are exported
  4. Other assemblies that this assembly depends on.
  5. Security permissions needed to run.
What is an assembly?

Assemblies are the building block of .NET framework applications; they form the fundamental unit of deployment, version control, reuse, and activation scoping and security permissions.

What is the difference between an EXE and a DLL?

EXE is an executable file and can run by itself as an application whereas DLL is usually consumed by an EXE or by another DLL and we cannot run or execute DLL directly.

For example in .NET compiling a Console Application or a Windows Application generates EXE, whereas compiling a Class Library Project or an ASP.NET web application generates DLL. In the .NET framework, both EXE and DLL are called assemblies.
A DLL can be reused in the application whereas an exe file can never be reused in an application.
EXE stands for executable, and DLL stands for Dynamic Link Librar.

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-3.1#the-form-tag-helper

ASP.NET core Web API

INTRODUCTION – 1:58 Course Overview – 4:46 Application Architecture – 7:30 API DEMO CODING PART 1 – FIRST 2 API ENDPOINTS (GET / READ) – 10:10 Project Setup – 15:30 Create our Domain Model (Command) – 18:30 Build Our Repository Interface – 24:46 Implement our Repository Interface (Mock Reposiory) – 30:46 Create our Controller (CommandsController) – 35:59 Create 2x API Endpoints – 48:35 Using Dependency Injection CODING PART 2 – ENTITY FRAMEWORK & SQL SERVER – 55:35 Architecture Checkpoint – 56:58 Set Up SQL Server App Login – 1:00:36 Entityframework Packages – 1:03:48 Entityframework Toolset – 1:05:00 Create our Database Context (CommanderContext) – 1:08:33 Our Database Connecttion String – 1:13:42 Register our DB Context in Startup – 1:18:00 Create Migrations – 1:21:40 Cancel Migrations & revist Command Model – 1:23:10 Add Data Validations to Command Model – 1:24:49 Create Migrations (Again!) – 1:26:05 Run Migrations against Database – 1:28:04 Add Data to Database – 1:32:34 Revist Our Repository to use DB Context CODING PART 3 – DATA TRANSFER OBJECTS & CREATE ENDPOINT – 1:41:11 Architecture Checkpoint – 1:42:01 Why Data Transfer Objects? – 1:48:34 AutoMapper Package & Startup Registration – 1:51:42 Create our first DTO – 1:53:40 Creating a mapping Profile – 1:57:07 Updating Our Action Results to use DTOs CODING PART 4 – PUT, PATCH & DELETE API ENDPOINTS – 2:04:14 Architecture Checkpoint – 2:05:40 Updating our Repository for Creating Resources – 2:12:14 Create a New DTO (for Creating) – 2:15:47 Create 3rd API Endpoint to Create Resources – 2:26:38 Use CreatedAtRoute to return 201 CreatedAtRoute – 2:35:07 Add Annotations to DTO to avoid 500 Errors – 2:44:10 Update Repository to Support Updates – 2:47:09 Add a New DTO (for Updating) – 2:50:08 Add 4th API Endpoint for Updating (PUT Request) – 2:52:56 Update our AutoMapper Profile – 3:00:58 Overview of PATCH – 3:05:00 Install 2x packages to support PATCH – 3:07:09 Update Startup – 3:08:43 Update our AutoMapper Profile (Final Update) – 3:09:39 Add 5th API Endpoint for Updating (PATCH Request) – 3:19:45 Add 6th API Endpoint for Deleting (DELETE Request) FINAL THOUGHTS & ACKNOWLEDGEMENTS – 3:25:31 Final Thoughts – 3:26:20 Patreon Supporter Credits

Sticky session refers to the feature of many commercial load balancing solutions for web-farms to route the requests for a particular session to the same physical machine that serviced the first request for that session. This is mainly used to ensure that a in-proc session is not lost as a result of requests for a session being routed to different servers. Since requests for a user are always routed to the same machine that first served the request for that session, sticky sessions can cause uneven load distribution across servers.

https://www.imperva.com/learn/availability/sticky-session-persistence-and-cookies/

What is the lifetime?

Transient

  • Makes an instance each time.
  • Never shared. 
  • Used for lightweight stateless services.

Singleton

  • Creates only single instance.
  • Shared among all components that demand it.

Scoped

  • Creates an instance once per scope.
  • Created on every request to the application.

ASP.NET Core – Dependency Injection

ASP.NET Core injects objects of dependency classes through constructor or method by using built-in IoC container.

The built-in container is represented by IServiceProvider implementation that supports constructor injection by default. The types (classes) managed by built-in IoC container are called services.

public IServiceProvider ConfigureServices(IServiceCollection services)
{
//
services.Configure(x =>
{
x.ValueLengthLimit = int.MaxValue;
x.MultipartBodyLengthLimit = int.MaxValue;
x.MultipartHeadersLengthLimit = int.MaxValue;

        });

        // MVC
        services.AddControllersWithViews(
                options =>
                {

                    options.Filters.Add(new AbpAutoValidateAntiforgeryTokenAttribute());
                    options.SuppressAsyncSuffixInActionNames = false;

                })
            .AddNewtonsoftJson(
                options =>
                {
                    //// Enum as string conversion to give Enum display values
                    options.SerializerSettings.Converters.Add(new StringEnumConverter());
                    options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                });

        #region AfterNugetupgrade21stJan2022

        services.AddApiVersioning(options =>
        {
            options.DefaultApiVersion = new ApiVersion(1, 0);
            options.AssumeDefaultVersionWhenUnspecified = true;
            options.ReportApiVersions = true;
        });

        services.AddVersionedApiExplorer(options =>
        {
            // add the versioned api explorer, which also adds IApiVersionDescriptionProvider service
            // note: the specified format code will format the version as "'v'major[.minor][-status]"
            options.GroupNameFormat = "'v'VVV";
            // note: this option is only necessary when versioning by url segment. the SubstitutionFormat
            // can also be used to control the format of the API version in route templates
            options.SubstituteApiVersionInUrl = true;
        });
        #endregion

        services.AddHttpClient(AppConsts.HelixHttpClientName);                  //Added from AppTemplate
        services.AddLogging();                                                    //Added from  AppTemplate
        services.AddDnaApp<HelixAppsConfiguration>(appConfiguration);         //Added from  AppTemplate
        services.AddTransient<IDbContextSchema>(x => { return new   });
        services.AddAbpDbContext<RosettaDbContext>(
                      );

        //for Redis cache
        services.AddCacheDependency(appConfiguration, StorageCacheType.RedisCache);

        //Bing in memory caching
        services.AddMemoryCache();

        //Bind Distributed Cache Settings Options
        services.Configure<CacheSettingsOptions>(appConfiguration.GetSection("DistributedCacheSettings"));

        var azureTableStorageCacheOptions = new AzureTableStorageOptions();


        //This section is needed regardless if CacheSettings:UseCache is true or false
        services.AddAzureTableStorageCache(options =>
        {
            
        });

        // Configure CORS for angular2 UI
        services.AddCors(
            options => options.AddPolicy(
              

            )
        );

        services.AddSwaggerDoc();

        // APP Insights
        services.AddApplicationInsightsTelemetry(appConfiguration.GetSection("ApplicationInsights").GetSection("InstrumentationKey").Value);

        // br compressor
        services.AddResponseCompression(options =>
        {
            options.EnableForHttps = true;
            options.Providers.Add<BrotliCompressionProvider>();
            options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[] { "image/svg+xml" });
            options.Providers.Add<GzipCompressionProvider>();
        });

        services.AddTransient<UsctProcessorResolver>(x => componentId =>
        {
            return UnderstandSCOTsProcessorHub.GetProcessorByComponentId(x, componentId);
        });

        // Configure Abp and Dependency Injection
        return services.AddAbp<GLAppWebHostModule>(
            // Configure Log4Net logging
            options => options.IocManager.IocContainer.AddFacility<LoggingFacility>(
                f => f.UseAbpLog4Net().WithConfig("log4net.config")
            )
        );

    }

There are basically two types of services in ASP.NET Core:

  1. Framework Services: Services which are a part of ASP.NET Core framework such as IApplicationBuilder, IHostingEnvironment, ILoggerFactory etc.
  2. Application Services: The services (custom types or classes) which you as a programmer create for your application.

In order to let the IoC container automatically inject our application services, we first need to register them with IoC container.

Configure

Inside of Configure method we set up middleware that handles every HTTP request that comes to our application:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)   //Added serviceProvider as extra from HelixAppTemplate
    {

        if (loggerFactory == null) throw new ArgumentNullException(nameof(loggerFactory));

        app.UseAbp(options => { options.UseAbpRequestLocalization = false; }); // Initializes ABP framework.

        app.UseCors(_defaultCorsPolicyName); // Enable CORS!

        app.UseResponseCompression();//Compression middleware before other middlewares which serves the files.

        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();

        app.UseAbpRequestLocalization(options =>
        {
            options.RequestCultureProviders.Insert(0, new GLAppRequestCultureProvider(new LoggerFactory()));
        });

        if (bool.TryParse(appConfiguration["App:RequestLogging"], out bool requestLogging) && requestLogging)
        {
            app.UseMiddleware<LogRequestMiddleware>();
        }

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();

            endpoints.MapControllerRoute(
                "api",
                "api/{controller}/{action}/{id?}");
        });

        app.UseSwaggerDoc(serviceProvider, appConfiguration);

        app.UseHsts();
        app.UseCookiePolicy(new CookiePolicyOptions { Secure = CookieSecurePolicy.Always });



    }

What is thread starvation

How IIS Process a Web Request?

In ASP.NET, web requests are processed by IIS. Once your request arrives at IIS, a thread (also known as Worker Thread) is taken from the CLR Thread Pool to process your request. Once your request’s processing completes, that thread is given back to the Thread Pool.

What is Thread Pool

A Thread Pool is a pool of threads or we can say a collection of threads.

What is Thread Starvation?

Now, suppose we have hosted our application on an IIS whose Thread-Pool’s size is 200. Now, assume that each web-request of our web-application takes 5 seconds to process. Now if 200 users simultaneously access our application, then all 200 worker threads will get busy for next 5 seconds. Now, some new user comes and tries to access our application (this is 201st user) then IIS will not be able to process this request because, all worker threads are already busy in processing previous requests. So, now IIS will wait some time for the threads to get free, if any thread gets free in the waiting time then it will be used to process our request otherwise IIS will return the user with the message 503 – Server Too Busy. This state is called Thread Starvation.

In small words, the condition or state when all the threads of the Thread Pool are in use and IIS don’t have any available or free thread to process a request, called the state of starvation & this is called Thread Starvation.

When does it happens?

It usually happens when your website’s traffic is very high.

For example, It may happen if you create an Online Examination System, on which thousands of users will give exam on the same time. So, you will have to write code in such manner that a thread should not block the request or should not take much time to process a request.

Solution: Async & Await

Main use of Async & Await in Web Applications is to free the thread. Async & Await will not run your code faster – this is a misconception that using Async & Await in code will run your code faster. They are used for scalability purpose. If you use Async & Await in your web-application properly, then it will make your application scalable enough to handle more requests with same resources.

I found below a better answer on What is use of Asnc/Await in web applications?

https://github.com/microsoft/vs-threading/blob/main/doc/threadpool_starvation.md

Why do we use configureawait while calling Async method. Difference between ConfigureAwait(True) & ConfigureAwait(False).

By default, when you use async/await, it will resume on the original thread that started the request. However, if another long-running process currently has taken over that thread, you will be stuck waiting for it to complete. To avoid this issue, you can use a method called ConfigureAwait with a false parameter. When you do, this tells the Task that it can resume itself on any thread that is available instead of waiting for the thread that originally created it. This will speed up responses and avoid many deadlocks.

With ConfigureAwait(true) (the default one), when you resume on another thread, the thread synchronization context is lost thus losing culture and/or language settings along with other things like HttpContext.Current (this happens in .NET Standard).

As a rule of thumb, you should always use ConfigureAwait(false) in library codes, and also in your code when you are multi-thread. This is an example as the default behaviour may not be suitable for most of the cases.

Caching Mechanism In ASP.NET Core

https://www.c-sharpcorner.com/article/caching-mechanism-in-asp-net-core/