Search This Blog

Saturday, November 28, 2020

Q16-Q20

Q16. Difference between concurrency and parallelism?
Q17. What is httpclientFactory?
Q18. Example of Nuget Middlewares, System inbuild middlewares?
Q19. Example of custom middlewares. 
Q20. Steps to implement Repository pattern with EntityFrameworkCore in dotnet 8?

=======================================================================
Q16. Difference between concurrency and parallelism?

Answer:
Concurrency - It means executing multiple tasks on same core. In this case the same core switches between multiple tasks and giving a feel that multiple tasks are excuting in parallel but in actual core is executing all of them little by little. Concurrency is a feel of parallelism. 

1. It is used to bring non blocking architecture. Means non of your task is blocked and the end user will keep seeing output of other tasks. The goal of this is not performance but making the feel of application as non blocking. This ensure to make application user friendly. 
2. its a async-await feature. In which the caller(the parent method, usually method of main class) doesn't wait for completion of child method  and move ahead. on getting data at await level, method thread will come back. 
3. Single thread picking multiple items to keep non blocking code. No good in performance but caller will not hanged up and remain unblocked. 

Parallelism -  Executing multiple tasks on multiple cores. 
1. It is used to bring parallelism 
2. Task is the feature. Threads are used as concept. Now it will create different threads for differnt task. 
3. It uses all cores present in system and give good performance. Multi threading is another word for it. 

For code level example and better understanding visit below
=======================================================================
Q17. What is httpclientFactory?

Answer:
A new HttpClientFactory feature comes with ASP.NET Core 2.1 which helps to solve some common problems that developers may run into when using HttpClient instances to make external web requests from their applications.

The main issue is when you create too many HttpClients within your code which can in turn into a problem ie socket Exhaustion. Where you have basically used up too many sockets too fast. There is a limit on how many sockets you can have open at one time. When you dispose of the HttpClient, the connection it had open remains open for up to 240 seconds in a TIME_WAIT state (in case any packets from the remote server still come through).

WATCH the youtube link for quick review. (IMP video)



=======================================================================
Q18. Example of Nuget Middlewares, System inbuild middlewares?

Answer:

Nuget:
EntityFrameworkCore
CORS

Framework:
UseStaticFiles
UseRouting
UseAuthorization
UseAuthentication

=======================================================================
Q19. Example of custom middlewares. 

Answer:
We have custom middleware for acknowledgement. We have 3rd party service which is giving inbound json data to our api. We have a middleware which send acknowledge of reading that json file and processing all the data correctly or not. so that 3rd party service is aware of proper data flow.  

=======================================================================
Q20. Steps to implement Repository pattern with EntityFrameworkCore in dotnet 8?

Answer:
1. Create dotnet core project and install nuget packages

dotnet new webapi -n MyNewApp
cd MyNewApp

dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools

2. Define entity class and create a DBContext class. Give reference of entity class as DbSet property in DBContexct class. 

3. Define IMyRespository and implement MyRepositoryClass

4. Register the Repository in DIContrainer in program.cs class
5. Inject the Repository in Controller Constructor and use it for calling methods. 
=======================================================================

Q11-Q15

Q11. What is [AllowAnonymous] Attribute in dotnet 8?
Q12. What are the benefits of .net core application over asp.net applications?
Q13. Describe the usage of Program.cs in dotnet 8 application?
Q14. How to create Custom middleware in dotnet 8?
Q15. What is the difference between calling a method in async and multi-threading?
=======================================================================
Q11. What is [AllowAnonymous] Attribute in dotnet 8?

Answer:
This attribute allows unauthenticated users to access specific actions, even if the controller is secured with [Authorize]. eg 
Login Page, 
Register Page
Logout etc

=======================================================================
Q12. What are the benefits of .net core application over asp.net applications?

Answer:
asp.net
1. Build for Windows only. 
2. Multiple versions per machine
3. Not open-source
4. Require external IOC container. 
5. Can be hosted only on IIS
6. Containerization is possible with limitation (only windows container and not cross platform)
7. Relatively slower
8. asp.net is not the first choice of microservices. 


.net Core
1. Build for Windows, macOS, or Linux and is platform independent. 
2. Multiple versions per machine.
3. Open-Source - It is an open-source and community-focused web framework.
4. Support Built-In Dependency Injection - It supports built-in Dependency Injection.
5. Hosting - It has the ability to host on IIS, Apache, Docker, nginx, or Self Hosting
6. Containerization is possible thus you can move your application on docker and then on kubernetes. 
7. Relatively faster. 
8. Microservices 

=======================================================================
Q13. Describe the usage of Program.cs in dotnet 8 application?

Answer:
In .NET 8, Program.cs is the entry point of the application. It uses the minimal hosting model, so there’s no longer a separate Startup.cs. Everything — dependency injection (DI), middleware, configuration, and routing — is set up directly in Program.cs.

Typical Usage:

  1. Create the builder and register services

    • builder.Services is used to register dependencies, controllers, authentication, EF DbContext, etc.

    var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddDbContext<MyDbContext>(); builder.Services.AddAuthentication(...).AddJwtBearer(...);
  2. Build the application

    var app = builder.Build();
  3. Configure the middleware pipeline

    • Middleware like authentication, authorization, exception handling, static files, Swagger, etc. are configured in order.

    app.UseHttpsRedirection(); app.UseAuthentication(); app.UseAuthorization();
  4. Map endpoints

    • Controllers, minimal APIs, health checks, etc. are wired here.

    app.MapControllers(); app.MapGet("/hello", () => "Hello from .NET 8!");
  5. Run the app

    app.Run();

=======================================================================
Q14. How to create Custom middleware in dotnet 8?

Answer:
1. Visual Studio include a template to create a custom middleware. Right click on a project and add a new item of type middleware. 
2. A new Middleware class will be generated with Constructor, Invoke Method, and an Extension method. This Extension method will be responsible to make my new middleware capable of getting added in program.cs pipeline. 
3. Register the middleware in pogram.cs

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseCustomMiddleware();

=======================================================================
Q15. What is the difference between calling a method in async and multi-threading?

Answer:
A-Synchronicity and parallelism are two different concepts. 
Async is to make request non-blocking, and it is single thread by default. it means we are not stopping caller to move ahead in code. this is concept of concurrency. Async await keyword can be used. 


Parallelism, or use of all threads is use of all cores and their threads. this is usually done to bring performance. for multi core system we can have parallelism in picture. Task is the keyword for parallelism. this is the concept of parallelism (not concurrency)


Thursday, November 5, 2020

Q6-Q10

Q6. How to implement CORS in .net core?
Q7. What are different types of services lifetime in microservices. Explain each of them?
Q8. How we can inject service dependency into controller?
Q9. Difference between inprocess and OutOfProcess hosting in .net core?
Q10. When we can use kestral server alone why we need reverse proxy server?
-----------------------------------------------------------------------------------------------------------------------------
Q6. How to implement CORS in dotnet 8?

Answer:
Full form of CORS is cross origin resource sharing. 
Implementing CORS in middleware is the most common practice in dotnet 8 applications

MiddleWare CORS

Step 1:
>> Install Nuget package "Microsoft.AspNetCore.Cors"

Step 2:
>> Add CORS service in program.cs

Step 3:
>> Use CORS middleware


-----------------------------------------------------------------------------------------------------------------------------
Q7. What are different types of services lifetime in microservices. Explain each of them?

Answer:
In .NET microservices, we configure service lifetimes in the Dependency Injection (DI) container, usually inside the Program.cs (in .NET 6+) or Startup.cs (older versions).
We use methods like:

services.AddSingleton<IMyService, MyService>();
services.AddScoped<IMyService, MyService>();
services.AddTransient<IMyService, MyService>();

Types of Service Lifetimes

Singleton 🟢

  • Created only once for the entire application lifetime.
  • Same instance is shared across all requests and users.
  • Example: Caching service, configuration reader.

Scoped 🟡
  • Created once per request (scope).
  • The same instance is reused within a single request but a new one is created for each new request.
  • Example: Database context (DbContext) in web APIs.

Transient 🔵
  • Created every time it’s requested.
  • Best for lightweight, stateless services.
  • Example: Utility services like email formatters, logging helpers.
-----------------------------------------------------------------------------------------------------------------------------
Q8. How we can inject service dependency into controller.

Answer:

Step 1: Create the Interface and the service itself

 public interface IHelloWorldService
 {
  string SaysHello();
 }
 
 public class HelloWorldService: IHelloWorldService
 {
  public string SaysHello()
  { 
   return "Hello ";
  }
 }
Step 2: Register the Service in DI Container

var builder = Webapplication.CreateBuilder(args);

//Register the service
builder.services.AddTransient<IHelloWorldService, HelloWorldService>();

Step 3: Inject the service into Controller

[ApiController]
[Route("api/controller")]

public class HomeController: ControllerBase
{
   private readonly IHelloWorldService _helloWorldService;

    public HomeController(IHelloWorldService helloWorldService)
    {
        _helloWorldService = helloWorldService;
    }
}


-----------------------------------------------------------------------------------------------------------------------------
Q9. Difference between inprocess and OutOfProcess hosting in .net core?

Answer:
In dotnet 8 InProcess and OutOfProcess are two hosting models for applications. 

InProcess Hosting:
>> InProcess hosting runs the ASP.NET Core application within the same process as the IIS worker process (w3wp.exe or iisexpress.exe).
>> This model provides improved performance because it avoids the overhead of proxying requests between IIS and the Kestrel server. Requests are handled directly within the IIS process.
>> Visual studio (not .net core CLI) Default hosting is InProcess. 
>> To configure InProcess hosting, set the <AspNetCoreHostingModel> property to InProcess in the project file (.csproj)

Outofprocess
>> OutOfProcess hosting runs the ASP.NET Core application in a separate process from the IIS worker process. The application runs on the Kestrel server, and IIS acts as a reverse proxy.
>> The internal web server is Kestrel, the external web server (also called reverse proxy server) can be IIS, Nginx or Apache.
>> To configure OutOfProcess hosting, set the <AspNetCoreHostingModel> property to OutOfProcess in the project file (.csproj):

-----------------------------------------------------------------------------------------------------------------------------
Q10. Why cannot we use Kestral server alone? Why we need reverse proxy server?

Answer:

The Kestrel Web Server can also be used with the combination of a reverse proxy server such as IIS, Apache, or Nginx. Now the question that should come to your mind is, If Kestrel can be used by itself as a web server which can directly handle and process the incoming HTTP Request, then why do we need a reverse proxy server?

This is because the reverse proxy server provides an additional layer of configuration and security which is not available with the Kestrel Server. It also maintains the load balancing. So, it is a good choice to use Kestrel Server along with a reverse proxy server

-----------------------------------------------------------------------------------------------------------------------------

Sunday, October 25, 2020

Q1-Q5

Q1. What is middleware in dotnet 8 ?
Q2.What is the High-Level Flow of Authentication and Authorization in dotnet 8 applications?
Q3. Difference app.Use(), app.next(), app.map(), app.mapwhen(), app.run() in dotnet 8?
Q4. Suppose you have created a service and its interface. You have imported that to your controller class but while making an api request. it is not hitting that particular service?
Q5. How to stop a controller from getting called?
-----------------------------------------------------------------------------------------------------------------------------
Q1. What is middleware in dotnet 8?

Answer:
In .NET 8, middleware is a lightweight component in the request pipeline that can processes every incoming HTTP requests and every outgoing responses.

Middleware are executed in the order they are registered in the pipeline. Most of them call the next middleware in the chain via a delegate(app.use and app.next), while some (like app.Run) can short-circuit the pipeline and it will stop the further calling. 

You can use built-in middleware (e.g., UseRouting, UseAuthentication, UseAuthorization) or create custom middleware by implementing a class with an Invoke or InvokeAsync method.

With .NET 8’s minimal hosting model, middleware are typically configured in the Program.cs file using extension methods like app.Use(...), app.Map(...), app.MapWhen(...)or app.Run(...).


-----------------------------------------------------------------------------------------------------------------------------
Q2. What is the High-Level Flow of Authentication and Authorization in dotnet 8 applications?

Answer
The high-level flow of authentication and authorization in .NET 8 is as follows:

1. Authentication (Identity Establishment)

  • A client first authenticates by presenting credentials—this could be username/password through a login API, an API key, or a federated login (e.g., OpenID Connect).

  • If credentials are valid, the server issues a security token (commonly a JWT). The token contains identity details and claims (e.g., user id, email, roles).

{
  "sub": "12345",
  "name": "Himanshu Goel",
  "role": "Admin",
  "exp": 1727467200
}
2. Token Storage & Requesting APIs
  • The client stores the token (e.g., in local storage, session storage, or cookies).
  • For subsequent API calls, the client includes the token in the Authorization header:
  • Authorization: Bearer <token>

3. Pipeline Validation via Middleware
  • The Authentication middleware validates the token (signature, expiry, issuer, audience). If invalid, the request is rejected.

  • Once authenticated, the Authorization middleware inspects the claims to enforce policies, roles, or custom requirements. Controllers or endpoints decorated with [Authorize] are protected, while [AllowAnonymous] bypasses checks.
[Authorize(Roles = "Admin")]
public IActionResult GetAdminData() { ... }

4. Program.cs Setup (Minimal Hosting Model in .NET 8) 
         var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication("Bearer")
    .AddJwtBearer("Bearer", options => { 
        options.TokenValidationParameters = ...; 
    });
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

-----------------------------------------------------------------------------------------------------------------------------
Q3. Difference app.Use(), app.next(), app.map(), app.mapwhen(), app.run() in dotnet 8?

Answer:
With app.Use may call next middleware component in the pipeline. 

On the other hand, middleware defined using app. Run will never call subsequent middleware and terminates the pipeline. 


1. app.Use()
2. app.next()

for app.use() and app.next()

What it does: Adds a middleware to the pipeline.
That middleware can do some work before passing the request along, and then also do work after the next middleware finishes.
Example: logging, authentication, error handling.

app.Use(async (context, next) =>
{
    Console.WriteLine("Before next middleware");
    await next(); // pass control to the next middleware
    Console.WriteLine("After next middleware");
});
------------------
3. app.map()
Used for branching the pipeline based on a fixed path.
app.Map("/api", apiApp =>
{
    apiApp.Run(async ctx => await ctx.Response.WriteAsync("API branch"));
});
-----------------------
4.app.mapwhen()
Like Map, but branches based on a predicate instead of a fixed path.
app.MapWhen(
    ctx => ctx.Request.Query.ContainsKey("debug"),
    debugApp =>
    {
        debugApp.Run(async ctx =>
            await ctx.Response.WriteAsync("Debug branch"));
    });

-----------------------
5. app.Run()
Registers a terminal middleware.
-----------------------------------------------------------------------------------------------------------------------------
Q4.  In dotnet 8 applications suppose you have created a service and its interface. You have imported that to your controller class but while making an api request, it is not hitting that particular service. What could the possible reason and solution?

Answer:

One major reason could be "Service Registration" missing. Ensure to register interface in program.cs page using AddScoped, AddSingleton, AddTransient

builder.services.AddScoped<IMyService, MyService>();

-----------------------------------------------------------------------------------------------------------------------------
Q5. How to stop a controller from acting like a controller class?

Answer:
So in .NET 8, a class will act like a controller if:
  • It’s decorated with [ApiController] or [Controller], or
  • It has routing attributes ([Route], [HttpGet], etc.), or
  • It inherits from Controller or ControllerBase.
To make it stop being treated as a controller, you remove those attributes/inheritance or filter it out in Program.cs when registering controllers.

Q36-Q40(EF)

Q36.  What is the difference between Include and Join in entity framework? Q37. What will be your approach in case you want to call a manual...