Showing posts with label ASP.NET. Show all posts
Showing posts with label ASP.NET. Show all posts

Caching in ASP.NET Core.

Caching is the technique of storing frequently accessed data in temporary fast storage so that future requests can be served faster without repeatedly calling a slow source like a database or external API.

👉 In simple words: Cache = Fast memory that avoids repeated expensive operations

Without caching:

  • Every request hits the database
  • Higher response time
  • Increased load on DB
  • Poor scalability

With caching:

  • Faster response time
  • Reduced database calls
  • Better scalability
  • Lower infrastructure cost

Imagine a restaurant menu:
  • ❌ Without cache → Chef cooks every dish from scratch every time
  • ✅ With cache → Popular dishes are pre-prepared and served instantly
That pre-prepared dish = Cache

How does caching work?
  1. Client requests data
  2. Application checks the cache first
  3. If found → return from cache (cache hit)
  4. If not found → fetch from DB, store in cache (cache miss)

Types of Caching in ASP.NET Core

There are two main types you must know as a .NET developer:
  • In-Memory Cache
  • Distributed Cache

In-Memory Caching.

In-Memory Cache stores data in the RAM of the application server.

  • Lives inside the application process
  • Very fast
  • Data is lost when the app restarts
How To Implement In-Memory Caching?

Step 1: Register Memory Cache.
builder.Services.AddMemoryCache();

Step 2: Inject IMemoryCache
using Microsoft.Extensions.Caching.Memory;

public class ProductService
{
    private readonly IMemoryCache _cache;

    public ProductService(IMemoryCache cache)
    {
        _cache = cache;
    }
}

Step 3: Cache Data Using Cache-Aside Pattern
public List<string> GetProducts()
{
    const string cacheKey = "products";

    if (!_cache.TryGetValue(cacheKey, out List<string> products))
    {
        // Simulate DB call
        products = GetProductsFromDatabase();

        var cacheOptions = new MemoryCacheEntryOptions()
            .SetAbsoluteExpiration(TimeSpan.FromMinutes(5))
            .SetSlidingExpiration(TimeSpan.FromMinutes(2));

        _cache.Set(cacheKey, products, cacheOptions);
    }

    return products;
}
When to Use In-Memory Cache:
  • Small applications
  • Single server apps
  • Lookup / static data
  • Config values
  • Not suitable for load-balanced systems

Distributed Caching.

Distributed Cache stores data in a separate cache server shared across multiple application instances.
Common implementations:
  • Redis
  • SQL Server Cache
  • NCache
Let's understand in detail, with Redis as an example, because it is one of the most popular Caching System.

Redis is an in-memory distributed cache used to:
  • Share cached data across multiple app instances
  • Improve performance
  • Reduce database load
👉 Unlike in-memory cache, Redis works in load-balanced & microservice environments.

Prerequisites
  • Option 1: Run Redis using Docker (Port: 6379)
  • Option 2: Local Redis
Step 1: Install Required NuGet Packages
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis

Step 2: Configure Redis in ASP.NET Core
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration =
        "my-redis.xxxxxx.use1.cache.amazonaws.com:6379";

    options.InstanceName = "MyApp:";
});

Step 3: Use Redis via IDistributedCache (Service Layer).
using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;

public class ProductService
{
    private readonly IDistributedCache _cache;

    public ProductService(IDistributedCache cache)
    {
        _cache = cache;
    }

Step 4: Cache-Aside Pattern Implementation.
public async Task<List<Product>> GetProductsAsync()
{
    const string cacheKey = "products";

    var cachedData = await _cache.GetStringAsync(cacheKey);

    if (cachedData != null)
    {
        return JsonSerializer.Deserialize<List<Product>>(cachedData);
    }

    // Simulate DB call
    var products = GetProductsFromDatabase();

    var options = new DistributedCacheEntryOptions
    {
        AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10),
        SlidingExpiration = TimeSpan.FromMinutes(2)
    };

    await _cache.SetStringAsync(
        cacheKey,
        JsonSerializer.Serialize(products),
        options
    );

    return products;
}

Step 5: Cache Invalidation
public async Task UpdateProductAsync(Product product)
{
    // Update DB logic

    await _cache.RemoveAsync("products");
}
Note: Caching without invalidation is a bug, not a feature.

How To Implement Logging in ASP.NET Core.

Logging is the process of recording application events so you can:

  • Debug issues
  • Monitor behavior
  • Trace requests
  • Audit actions in production

Without proper logging:

  • Bugs are hard to reproduce
  • Production failures are invisible
  • Root cause analysis becomes guesswork

ASP.NET Core has ILogger built in via Microsoft.Extensions.Logging. Supported Providers (by default)
  • Console
  • Debug
  • EventSource
  • Application Insights (Azure)
Rule: Never log everything as Information.

How To Use ILogger?

Step 1: Inject ILogger.
public class OrderController : ControllerBase
{
    private readonly ILogger<OrderController> _logger;

    public OrderController(ILogger<OrderController> logger)
    {
        _logger = logger;
    }
}

Step 2: Log Messages
_logger.LogInformation("Order creation started");

_logger.LogWarning("Order {OrderId} has no items", orderId);

_logger.LogError(exception, "Failed to create order {OrderId}", orderId);

Good Option 1: Logging Exception Correctly.
catch (Exception ex)
{
    _logger.LogError(ex, "Error while processing order {OrderId}", orderId);
    throw;
}
👉 Always pass the exception object to preserve stthe ack trace.

Good Option 2: Logging in Middleware.
public async Task InvokeAsync(HttpContext context)
{
    _logger.LogInformation(
        "Request {Method} {Path}",
        context.Request.Method,
        context.Request.Path);

    await _next(context);

    _logger.LogInformation(
        "Response {StatusCode}",
        context.Response.StatusCode);
}

Built-in logging is good, but Serilog is preferred in production because it provides:
  • Rich structured logging
  • Multiple sinks (File, DB, Seq, Elastic)
  • Better performance & flexibility
Step 1: Install Packages
dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Sinks.Console
dotnet add package Serilog.Sinks.File

Step 2: Configure Serilog in Program.cs
using Serilog;

Log.Logger = new LoggerConfiguration()
    .Enrich.FromLogContext()
    .WriteTo.Console()
    .WriteTo.File("Logs/app-.log", rollingInterval: RollingInterval.Day)
    .CreateLogger();

builder.Host.UseSerilog();

Step 3: Use ILogger as Usual.
_logger.LogInformation("Invoice {InvoiceId} generated", invoiceId);
You still use ILoggerSerilog works behind the scenes.

Interview Answer: In ASP.NET Core, I use ILogger for application logging and Serilog for structured, production-grade logging. I follow proper log levels, structured messages, correlation IDs, and centralized log storage to ensure observability and easy debugging.

Implement Custom Global Exception Handling in ASP.NET Core.

Exception handling is one of the most important non-functional requirements (NFRs) in any backend application. In ASP.NET Core, poor exception handling leads to:
  • Application crashes
  • Inconsistent error responses
  • Security risks (stack traces exposed)
  • Difficult debugging and monitoring
To solve this, ASP.NET Core promotes Global Exception Handling, where all unhandled exceptions are caught at a single place, logged, and converted into a consistent HTTP response.

This article explains:
  • Why is global exception handling needed
  • How to implement a custom global exception middleware
  • Best practices used in production systems

Why Do We Need Global Exception Handling?

Before understanding Global Exception, we need to know what an exception is and why we need to handle it properly.

An exception is a runtime error that occurs when the application cannot continue normal execution.
Examples:
  • Database connection failure
  • Null reference access
  • Invalid user input
  • External API timeout

If exceptions are not handled properly, they can:
  • Crash the application
  • Leak sensitive information
  • Return inconsistent responses
  • Make debugging extremely difficult
Global Exception Handling is a centralized mechanism that:
  • Catches all unhandled exceptions in one place
  • Logs them consistently
  • Converts them into a standard HTTP response
  • Prevents sensitive details from reaching clients
Instead of handling errors locally in every controller or method, the application handles them globally.

Let's understand the benefits of Global Exception Handling in detail with an example:

Example 1: Error Message Without Global Exception Handler.
{
  "error": "Object reference not set to an instance of an object"
}

Worse Case:
System.NullReferenceException at OrderService.cs line 42
Issues
  • Internal code details exposed
  • Frontend doesn’t know how to handle different formats
  • Logs may be missing or incomplete
Example 2: Error Message With Global Exception Handler.
{
  "statusCode": 400,
  "message": "Invalid request",
  "traceId": "abc123"
}
APIs always return a consistent response.

Imagine a building security desk:
  • Without global handling → every room handles its own security
  • With global handling → one central security desk handles all issues
This is exactly how Global Exception Handling works.
Interview Answer: Global exception handling is needed to centrally catch all unhandled exceptions, return consistent and secure error responses, improve maintainability, and enable reliable logging without duplicating try–catch blocks across the application.

 How To Handle Exceptions in ASP.NET Core?

ASP.NET Core provides multiple ways to handle exceptions, but not all are equal. A senior .NET developer is expected to choose the right approach based on maintainability, security, and scalability.

1. Try-Catch Block in Controller: Handling exceptions inside each controller action using try–catch.

[HttpGet("{id}")]
public IActionResult GetProduct(int id)
{
    try
    {
        var product = _service.GetProduct(id);
        return Ok(product);
    }
    catch (Exception ex)
    {
        return StatusCode(500, ex.Message);
    }
}
Problem:
  • Code duplication: try–catch in every action
  • Inconsistent responses: Different error formats
  • Security risk: Exception messages exposed
  • Poor separation: Business + error handling mixed
  • Hard to maintain: Changes needed everywhere

2. UseExceptionHandler() Middleware: Built-in middleware provided by ASP.NET Core for basic global exception handling.
app.UseExceptionHandler(errorApp =>
{
    errorApp.Run(async context =>
    {
        context.Response.StatusCode = 500;
        await context.Response.WriteAsync("Something went wrong");
    });
});
Problem:
  • Limited customization
  • No exception type mapping
  • No structured response
  • Not ideal for APIs
3. Custom Exception Middleware: A custom middleware that intercepts all unhandled exceptions, logs them, and returns a standard response.

Step 1: Create Custom Exceptions.
public class NotFoundException : Exception
{
    public NotFoundException(string message) : base(message) { }
}

Step 2: Create Error Response Model.
public class ErrorResponse
{
    public int StatusCode { get; set; }
    public string Message { get; set; }
    public string TraceId { get; set; }
}

Step 3: Create Middleware
public class GlobalExceptionMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<GlobalExceptionMiddleware> _logger;

    public GlobalExceptionMiddleware(RequestDelegate next, ILogger logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Unhandled exception");

            int statusCode = ex switch
            {
                NotFoundException => 404,
                _ => 500
            };

            var response = new ErrorResponse
            {
                StatusCode = statusCode,
                Message = statusCode == 500 ? "Internal error" : ex.Message,
                TraceId = context.TraceIdentifier
            };

            context.Response.StatusCode = statusCode;
            context.Response.ContentType = "application/json";
            await context.Response.WriteAsJsonAsync(response);
        }
    }
}

Step 4: Register Middleware
app.UseMiddleware<GlobalExceptionMiddleware>();

4. IExceptionHandler: A new interface-based global exception handling mechanism introduced in .NET 7.

Step 1: Step 1: Implement IExceptionHandler.
public class GlobalExceptionHandler : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(
        HttpContext context,
        Exception exception,
        CancellationToken cancellationToken)
    {
        context.Response.StatusCode = exception switch
        {
            NotFoundException => 404,
            _ => 500
        };

        await context.Response.WriteAsJsonAsync(new
        {
            message = "Error occurred",
            traceId = context.TraceIdentifier
        }, cancellationToken);

        return true;
    }
}

Step 2: Register Service.
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();

Step 3: Enable Middleware.
app.UseExceptionHandler();

Benefits:
  • Clean & structured
  • Official Microsoft approach
  • Easy integration with ProblemDetails
  • Less boilerplate
Interview Answer: For production-grade ASP.NET Core APIs, I prefer custom global exception middleware because it gives full control over exception mapping, logging, and response structure. For newer .NET versions, IExceptionHandler is also a clean and modern alternative.

launchSetting.json File in ASP.NET Core.

When you're building ASP.NET Core applications, your focus is usually on the core logic, APIs, UI, or database layers. But there's one small file quietly sitting in your project that can significantly improve your development experience, and that's the launchSettings.json file.

Suppose you've ever wondered how your app knows which port to run on, how to open Swagger by default when debugging, or how to simulate different environments like Development or Staging without changing your code. In that case, you're about to find your answer.

In this guide, you’ll learn what the launchSettings.json file does, how you can customize it, and how to use it to streamline your development workflow. Whether you're using Visual Studio, Visual Studio Code, or the .NET CLI, mastering this file will help you build, run, and test your applications more efficiently. Let's dive in!

What is launchSettings.json?

launchSettings.json is a development-only configuration file used by Visual Studio, Visual Studio Code, and the .NET CLI. It defines how your ASP.NET Core app starts during development, including which port to use, which server to run on (Kestrel or IIS Express), whether to open a browser, and even which environment variables to set.

This file allows you to configure:
  • Which server to use (like Kestrel or IIS Express)
  • What ports or URLs should your app listen to
  • Whether a browser should open when debugging starts
  • What environment variables should be set (like ASPNETCORE_ENVIRONMENT)
  • Which launch profile should be used (for different debugging scenarios)

It’s important to know that launchSettings.json is not used in production, and it only affects how your app runs locally while developing and debugging.

Where to Find launchSettings.json in ASP.NET Core?

When you create a new ASP.NET Core project using Visual Studio or the .NET CLI, a file named launchSettings.json is automatically created for you.

Path to Find:
YourProjectFolder/
└── Properties/
    └── launchSettings.json

So if your project is named MyWebApp, you’ll find the file at:
MyWebApp/Properties/launchSettings.json

launchSettings.json file path

If it's missing, don’t worry — you can create it manually inside the Properties folder, or let Visual Studio regenerate it by enabling project debugging or launch profiles.

Understanding the Structure of launchSettings.json.

launchSettings.json structure is designed around the concept of profiles, each representing a different way your app can be launched, such as through Kestrel, IIS Express, or Docker.

launchSettings.json File
{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:9866",
      "sslPort": 0
    }
  },
  "profiles": {
    "http": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "http://localhost:5155",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
Now let’s break down each part in detail.

1. Profiles Section

At the heart of the file is the profiles object. Think of each profile as a self-contained configuration unit that describes a launch mode.
  • Each profile has a name (e.g., "IIS Express", "MyApi").
  • Profiles are typically tied to how the developer intends to run or test the application in a specific context.
  • You might have one profile for API testing and another for UI debugging, all isolated yet contained in the same file.
You can select your profile from the start button of Visual Studio as shown below:

launchSettings.json profile Setting

2. commandName

The commandName within a profile acts as the execution strategy. It determines what kind of host will launch your app.
Theoretical values include:
  • "Project": Indicates the app should run using the default Kestrel web server.
  • "IISExpress": Used when the app is hosted via IIS Express (Windows-specific).
  • "Docker": Used when your app is containerized and launched via Docker tools.
  • "Executable": Allows launching an external executable instead of a .NET project.
This abstraction allows your launch profiles to be agnostic of infrastructure and geared more toward intention (e.g., "run my app inside a container" vs. "run using the built-in server").

3. applicationUrl

This element defines the network bindings for the application during development. It tells the development host (like Kestrel) which ports and protocols (HTTP/HTTPS) the application should listen on.

The presence of both HTTP and HTTPS reflects:
  • A need for secure local testing
  • Compatibility with different local service consumers
  • Simulation of real-world hosting conditions

4. launchBrowser & launchUrl

These two elements describe the startup behavior of your development session:
  • launchBrowser specifies whether to automatically open a browser.
  • launchUrl defines the path or endpoint that the browser should navigate to after the app starts.
This abstracts the idea of launching your app into a specific state — such as the Swagger UI for APIs — giving you control over the first interaction with your running application.

5. environmentVariables

Environment variables represent runtime configuration values that are injected into the app process when launched.

From a theoretical view:
  • They enable environment-specific behaviors (e.g., showing debug info in Development mode).
  • They act as a loose coupling mechanism, allowing the app to adapt its behavior based on externalized values.
  • The primary variable you’ll often set is ASPNETCORE_ENVIRONMENT, which the ASP.NET Core framework uses to determine which appsettings.{Environment}.json file to load.
This section empowers you to simulate real-world deployment behaviors without altering code or core config files.

6. dotnetRunMessages

This optional flag enables diagnostic verbosity during command-line execution. It provides insight into listening addresses, host readiness, and runtime logs useful during CLI-based workflows.

Theoretically, this enhances developer observability during local execution and supports script-driven environments (CI/CD pipelines, custom launch scripts).

Bonus: Docker Launch Profile (Optional)
If you're using Docker, Visual Studio may add a profile like this:
"Docker": {
  "commandName": "Docker",
  "launchBrowser": true,
  "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger"
}

The {Scheme}, {ServiceHost}, and {ServicePort} are dynamically replaced during container startup.

Summary

You can think of launchSettings.json as your local run configuration manager. It lets you:
  • Control how your app launches (Kestrel, IIS Express, Docker)
  • Set URLs, ports, and environments
  • Auto-launch your browser to specific routes
  • Inject custom environment variables for development
  • Keep multiple profiles for different test and debug scenarios
Once you get comfortable with its structure, you’ll find it much easier to control and optimize your development setup.

ASP.NET Core Tutorial

In this course of ASP.NET Core, we will cover all the basic, intermediate, and advanced ASP.NET core concepts that help you build data-driven web applications by the end of this course you will be able to perform all the CRUD operations that are Create, Read, Update and Delete using Sequal server as our database. 

The topics which we are going to cover in detail are-

  • ASP.NET Core.
  • ASP.NET Core MVC.
  • ASP.NET Core Identity.
  • Entity Framework Core.

What is ASP.NET Core?

ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern, cloud-based, Internet-connected applications. ASP.NET Core is a redesign of ASP.NET 4.x and earlier it was named ASP.NET 5 and later is renamed ASP.NET Core.

Few benefits and features of ASP.NET Core.

Cross-Platform: ASP.NET Core applications can be developed and run across different platforms like Windows, macOS, Linux. ASP.NET Core applications can be hosted on IIS, Apache, Docker, and even Self-host in your own process.

Because of One Unified Programming Model for MVC and Web API, both the MVC Controller class and the ASP.NET Web API Controller class inherit from the same Controller base class and returns IActionResult.

ASP.NET Core has great build-in support for Dependency Injection which is a very great feature to learn.

ASP.NET Core Testability feature makes unit testing easy for developers.

It is an Open Source technology so it is continuously growing and improving with the support of developers from the open-source community.

Modular: ASP.NET Core provides modularity with Middleware Components. Both the request and response pipelines are composed using the middleware components. A rich set of built-in middleware components are provided out of the box. Custom Middleware Components can also be created.

Middleware - Is a piece of software that can handle HTTP request or response

Prerequisites for this course:

  • Basic understanding of HTML, CSS, and C#.
  • Prior MVC knowledge is helpful but not required. 

ASP.NET Core Project File.

.csproj or .vbproj depending on the programming language used.
No need to unload the project to edit the project file.
File or Folder references are no longer included in the project file.
The File System determines what files and folders belong to the project.

TargetFramework.
Specifies the target framework for the application.
To specify a target framework we used Target Framework Moniker (TFM)

AspNetCoreHostingModel.
Specifies how the application should be hosted.
InProcess or OutofProcess.
InProcess hosts the app inside of the IIS working process (w3wp.exe)
OutProcess hosting model forward web requests to a backend ASP.NET Core app running the Kestrel server. The default is OutofProcess hosting.

PackageReference.
Used to Include a reference to the NuGet package that is installed for the application.
Merapackage - Microsoft.AspNetCore.App
A metapackage has no content of its own. It just contains a list of dependencies (other packages).
When the version is not specified, an implicit version is specified by the SDK. Rely on the implicit version rather than explicitly setting the version number on the package reference. 

Main method in ASP.NET Core.
A Console application usually has a Main() method.
Why do we have a Main() method in ASP.NET Core Web Application?
ASP.NET Core application initially starts as a Console application.
This Main() method configures ASP.NET Core and starts it and at that point it becomes an ASP.NET Core web application.


The Main() method called "CreateWebHostBuilder" and we are passing the command line argument to it. We can notice that "
CreateWebHostBuilder" return "IWebHostBuilder" and "Build()" is called on that which build the webhost on which ASP.NET Core Application and on this we add "Run()" and start listening the incoming Http request.

We are also configuring the "Startup" class using the extension method named ".UseStartup"
Going to the definition of "Startup" class we find two important method "ConfigureService" configure the service required for our application and "Configure" configure our application request processing pipeline 

Some of the Tasks that CreateDefaultBuilder() performs.
Setting up the web server. Loading the host and application configuration from various configuration sources and Configuring logging.

An ASP.NET Core application can be hosted.
  • InProcess or 
  • OutofProcess.

ASP.NET Core InProcess Hosting.

To configure InProcess hosting.
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>

CreateDefaultBuilder() method calls UseIIS() method and host the app inside of the IIS worker process (w3wp.exe or iisexpress.exe)

InProcess hosting delivers significantly higher request throughput than OutOfProcess hosting 

To get the process name executing the app.
System.Diagnostics.Process.GetCurrentProcess().ProcessName

With out-of-process hosting.
2 Web Servers - Internal and External Web Server.
The internal web server is Kestrel.
The external web server can be IIS, Nginx, or Apache.

What is Kestrel?
Cross-Platform Web Server for ASP.NET Core.
Kestrel can be used, by itself as an edge server.
The process used to host the app is dotnet.exe.


Dependency Injection in ASP.NET Core.

What is Dependency Injection?
Dependency Injection (DI) is the technique to achieve IOC (Inversion of Control). Inversion of Control means we need to make our code loosely coupled so in the future if there are any changes then there should not be any tight coupling between any two classes of object.


This is the basic structure of our project when we are not using Dependency Injection and we are using some service(class) inside one or more Controller then we create an object of the service using the "new" keyword and suppose in the future if we make any changes like changing the name of the service then we have to make those changes inside all Controllers. This is an example of tightly coupling.


Now let's understand what happens when we work with Dependency Injection, suppose I have only one service so to work with dependency injection I need to create one interface of my service. Now I will not work directly with the service I will use an interface to create this field and to store the object of this particular service. Now if we are making any changes in service then we don't have to make any changes in the control which is using it.

Now one important question that may come to our mind that where I will create the instance of the service and how the application will come to know that this interface is resolved by using this particular class. ???

In the concept of dependency injection, we generally create a container, and inside that container, we define some settings. 

How to configure Dependency Injection in ASP.NET Core?


ASP.NET Core provides the built-in support for DI. Dependencies are registered in containers and the container in ASP.NET core is IServiceProvider. Services are typically registered in the application's Startup.ConfigureService method.

Service Lifetime.
Service can be registered with following lifetimes-
  • Transient (AddTransient<>) - A  new instance of the service will be created every time it is requested.
  • Scoped (AddScoped<>) - These are created once per client request. For each HTTP request
  • Singleton (AddSingleton<>) - Same instance for the application.

How a DotNet Program Execute ?

To understand how a DotNet program execution takes place we have to do the comparison between pre-Dotnet program execution with DotNet program execution. So before DotNet came into existence, we used to build the application using other programming languages like C++ or VB6. 

Let's, for example, build an application using VB6 and compile it using a language compiler then an assembly gets generated with .dll or .exe extension depending on the type of application. This assembly is in Native code or Machine code format. We have to do the compilation because our operating system doesn't understand high-level programming languages, they only understand binary code of 0s and 1s. So basically we deploy that assembly onto the system to get executed which is nothing but a native code. 

Now lets us understand what naive code means? Suppose you have Windows operating system and now you take the assembly which was compiled on the Windows operating system and try to run it on Linux or another operating system then it will give you an error because that code is native to only Windows operating system. That's why it is called Native code or Object code. This is the problem with the pre-DotNet application, they are not portable and we have to build different operating systems.

Now let's understand how a DotNet application executes. DotNet supports several programming languages like C#, VB, C++, etc. When you build a DotNet application using any of these languages and compile using the respective language compiler, we get an assembly here also but unlike pre-DotNet application, it does not contain native code, instead, it contains intermediate language. This is the main difference between a DotNet program and a Pre-DotNet program but your operating system cannot understand the intermediate language so we need a runtime environment name as CLR (Common Language Runtime) to convert the intermediate language to native code. 

Now the question is how does this CLR come in between to do this job? When we install DotNet on our system, we basically install two important components one is the DotNet framework class library and another one is CLR. This is like a heart for DotNet program execution. This CLR layer exists between Assembly and the Operating system. Within CLR there is a very important component named as JIT compiler which takes IL (Intermediate Language) as input and generates native code as the output for the Operating system. 

So the biggest advantage of the DotNet application is that is portable which means that the same code can run on any operating system with the help of CLR installed on that operating system. Another advantage of DotNet is that the runtime environment contains a garbage collector which will clean the object or memory that is not in use programmer doesn't have to worry much about memory management.

Note: The native code is not stored permanently anywhere after we close the program the native code is thrown away and when we execute the program again the native code will generate again. (alert-success)


 

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson