anitsh / til

Today I Learn (til) - Github `Issues` used as daily learning management system for taking notes and storing resource links.
https://anitshrestha.com.np
MIT License
78 stars 11 forks source link

ASP.NET Core Foundation #1014

Open anitsh opened 1 year ago

anitsh commented 1 year ago

The following diagram shows the complete request processing pipeline for ASP.NET Core MVC and Razor Pages apps. You can see how, in a typical app, existing middlewares are ordered and where custom middlewares are added. You have full control over how to reorder existing middlewares or inject new custom middlewares as necessary for your scenarios.

image

Lets see the basic files generated from commanline.

dotnet new web generates:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();

dotnet new razor generates more complete templates:

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();

WebApplication Class

The web application used to configure the HTTP pipeline, and routes.

Properties

Methods

Used RunAsync instead of Run. App probably ran in background. Could not find or locate it. NOT SURE WHAT HAPPENED!


While checking that found out that Tor process was running. sudo ss -tulpn | grep LISTEN

Stoped and disabled Tor from system processes. sudo systemctl stop tor sudo systemctl disable tor

ps aux | less : trying to understand what other things were running. XXX 4329 0.0 1.1 3986896 93540 ? Sl Dec23 0:09 .vscode/extensions/ms-dotnettools.csharp-1.25.2-linux-x64/.razor/rzls -l sp --trace 0

ps aux | grep 'vscode' USER 77012 0.0 0.0 9564 2372 pts/0 S+ 00:41 0:00 grep --color=auto vscode

Find the process/service listening on a particular port : fuser 80/tcp Find the process name using PID : ps -p 2053 -o comm=

Was curious on why VSCode was listed even after closing it.

ps aux | grep '*vscode*'
USER       77012  0.0  0.0   9564  2372 pts/0    S+   00:41   0:00 grep --color=auto *vscode*

ps -fp 2372
UID          PID    PPID  C STIME TTY          TIME CMD
USER        2372    2229  0 Dec23 ?        00:00:00 /usr/libexec/ibus-memconf

Four memory measurements used by processes in Linux; VSZ, RSS, USS, and PSS.

VSZ Memory VSZ is short for Virtual Memory Size. It’s the total amount of memory a process may hypothetically access. It accounts for the size of the binary itself, any linked libraries, and any stack or heap allocations. When a process is started, VSZ memory becomes RSS memory,

RSS Memory As opposed to VSZ, RSS, also short for Resident Set Size, is a measurement that shows how much RAM has been allocated to a process during its execution. But, it isn’t actually an accurate measurement for RAM usage for a process since it doesn’t take into account libraries already loaded in memory. If two processes use one or more libraries, then RSS will report the libraries’ sizes for each process, even though the libraries would be already loaded beforehand in the case of one process starting after another. This is why RSS can be misleading and shouldn’t be trusted completely. Because RSS shows the whole memory output, even for information that has already been preloaded, if we add up everything in the processes list, we’d get more memory than the total memory allocated.

PSS Memory PSS, or Proportional Set Size, is a much more useful memory management metric. It works exactly like RSS, but with the added difference of partitioning shared libraries. For example, if we have five processes using the same library with a size of 50 pages, for each process the size reported by PSS will have only 10 pages for that particular shared library. The same thing happens for all shared libraries for all shared processes. One advantage of PSS is that summing all the processes together, we get a good approximation of the whole memory usage in a system.

USS Memory The Unique Set Size, or USS, represents the private memory of a process. In other words, it shows libraries and pages allocated only to this process. This type of memory is also very useful, as it represents the actual cost of launching another process. And, vice versa, when a process ends, it represents the actual amount that is returned to the system.

ps eo user,pid,vsz,rss $(pgrep -f 'chrome')

smem | grep -w 'chrome'

More than one instance of VSCode extension was running ~/.vscode/extensions/ms-dotnettools.csharp-1.25.2-linux-x64/.razor/rzls Disabled vscode from snap to check if it would make any difference but it did not.

Inspecting the parent process : ps -ef --forest, showed process id 1762, which belonged to systemd.

user 32447 1762 0 Dec24 ? 00:00:08 _ /home/anit/.vscode/extensions/ms-dotnettools.csharp-1.25.2-linux-x64/.razor/rzls -lsp --trace user 35110 1762 0 Dec24 ? 00:00:07 _ /home/anit/.vscode/extensions/ms-dotnettools.csharp-1.25.2-linux-x64/.razor/rzls -lsp --trace user 65234 1762 0 Dec24 ? 00:00:05 _ /home/anit/.vscode/extensions/ms-dotnettools.csharp-1.25.2-linux-x64/.razor/rzls -lsp --trace a

user 1762 1 0 Dec23 ? 00:00:02 /lib/systemd/systemd --user

This is an official issue - https://github.com/dotnet/razor/issues/6556.

Attempting to reboot and check.

https://www.unixsysadmin.com/systemd-user-services

Middleware

Chain multiple request delegates together with Use.

When a web request is made,

Middleware = A sequence of request delegates that are called one after the other

How is the response to every HTTP request made?

image

The Endpoint middleware in the preceding diagram executes the filter pipeline for the corresponding app type—MVC or Razor Pages.

The Routing middleware in the above diagram is shown following Static Files. This is the order that the project templates implement by explicitly calling [app.UseRouting]. If we don't call app.UseRouting, the Routing middleware runs at the beginning of the pipeline by default

using IndividualAccountsExample.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddRazorPages();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
else
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
// app.UseCookiePolicy();

app.UseRouting();
// app.UseRequestLocalization();
// app.UseCors();

app.UseAuthentication();
app.UseAuthorization();
// app.UseSession();
// app.UseResponseCompression();
// app.UseResponseCaching();

app.MapRazorPages();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware

anitsh commented 1 year ago

Which one to use, AddTransient, AddScoped and AddSingleton Services

Transient objects are always different; a new instance is provided to every controller and every service. Scoped objects are the same within a request, but different across different requests. Singleton objects are the same for every object and every request.

Transient

since they are created every time they will use more memory & Resources and can have a negative impact on performance use this for the lightweight service with little or no state.

Scoped

better option when you want to maintain state within a request.

Singleton

memory leaks in these services will build up over time. also memory efficient as they are created once reused everywhere.

Use Singletons where you need to maintain application wide state. Application configuration or parameters, Logging Service, caching of data is some of the examples where you can use singletons.

Injecting service with different lifetimes into another

Never inject Scoped & Transient services into Singleton service. ( This effectively converts the transient or scoped service into the singleton.)

Never inject Transient services into scoped service ( This converts the transient service into the scoped.)

image