Showing posts with label DotnetCore. Show all posts
Showing posts with label DotnetCore. Show all posts

Wednesday, 20 November 2024

Entity Framework Vs Entity Framework Core

 The main differences between Entity Framework (EF) and Entity Framework Core (EF Core) stem from their architectural changes, cross-platform support, performance improvements, and additional features. Below are the key distinctions:

1. Platform Support:

  • Entity Framework (EF):
    • Primarily designed to run on the .NET Framework, which is Windows-only.
  • Entity Framework Core (EF Core):
    • Cross-platform: Works on Windows, Linux, and macOS. It runs on the .NET Core platform and .NET 5+.

2. Architecture:

  • Entity Framework (EF):
    • EF is tightly coupled with the .NET Framework and its libraries.
  • Entity Framework Core (EF Core):
    • EF Core is a rebuild of the original EF, designed to be lightweight and more modular. It is based on .NET Core and allows for greater flexibility, including easier integration with non-.NET technologies.

3. Performance:

  • Entity Framework (EF):
    • EF had performance issues, particularly with large datasets or complex queries.
  • Entity Framework Core (EF Core):
    • EF Core is generally faster than EF, thanks to a more efficient query pipeline, optimizations in database access, and better memory usage.

4. Features:

  • Entity Framework (EF):
    • Full support for features like Lazy Loading, Complex Types, Stored Procedures, and Model First (designing database schema in the model).
  • Entity Framework Core (EF Core):
    • EF Core introduced several new features but also lacks some features from the older EF version (though many of these have been reintroduced or are in progress). For example:
      • Support for SQL Server, SQLite, PostgreSQL, MySQL, etc.
      • No Lazy Loading by default (but it can be enabled).
      • Better support for LINQ queries, Global Query Filters, and In-memory database.
      • It now supports many-to-many relationships directly, unlike EF which needed manual mapping.
      • Migration system is more flexible.
      • No Model First or Database First support initially (though EF Core now supports some of it).

5. Database Providers:

  • Entity Framework (EF):
    • Limited to the SQL Server provider.
  • Entity Framework Core (EF Core):
    • Multiple database providers are available, including SQL Server, SQLite, PostgreSQL, MySQL, and even non-relational databases like Cosmos DB.

6. Migrations:

  • Entity Framework (EF):
    • Migrations in EF work based on database schema and model synchronization.
  • Entity Framework Core (EF Core):
    • Migrations are better structured and easier to manage in EF Core, especially for modern application requirements.
    • Command-line tools in EF Core make database migrations more manageable.

7. Community and Updates:

  • Entity Framework (EF):
    • EF is in a maintenance-only phase and is not receiving new major updates. It primarily supports applications that are still using .NET Framework.
  • Entity Framework Core (EF Core):
    • EF Core is actively developed and has a strong community around it, with regular updates and new features being added.

8. Compatibility and Support:

  • Entity Framework (EF):
    • Only supports .NET Framework projects, meaning it’s tied to older .NET versions.
  • Entity Framework Core (EF Core):
    • Works with both .NET Core and .NET 5+, making it suitable for modern applications.

9. Query Capabilities:

  • Entity Framework (EF):
    • Has robust querying capabilities, but some features were not as optimized as in EF Core.
  • Entity Framework Core (EF Core):
    • More optimized LINQ queries and better SQL generation.

10. Backward Compatibility:

  • Entity Framework (EF):
    • EF works with older .NET Framework projects but is limited in functionality compared to EF Core.
  • Entity Framework Core (EF Core):
    • Not backward compatible with EF (especially when migrating from EF 6.x to EF Core).

Summary:

  • Entity Framework (EF) is a mature ORM that was built for the .NET Framework and is more feature-rich in some areas but lacks the flexibility and performance improvements of EF Core.
  • Entity Framework Core (EF Core) is a modern, cross-platform ORM that is faster, more modular, and supports a wider variety of databases and deployment scenarios, but it is still catching up with certain features found in EF.

If you're developing new applications or migrating to .NET Core or .NET 5+, EF Core is generally the preferred choice. If you're working with legacy .NET Framework applications, EF may still be the better option.

Continue Reading →

Thursday, 7 November 2024

Disadvantages of .NET Core

 Here are some disadvantages of .NET Core:

  • Limited libraries and tools

.NET Core doesn't have as many libraries and tools as .NET Framework. 

  • Less community support

.NET Core has a smaller community of developers than .NET Framework, so it may be harder to find answers to problems. 

  • No support for web forms

.NET Core doesn't support web forms, so if your applications rely on them, you'll need to use .NET Framework or look for alternatives. 

  • Some technologies are not available

Some .NET Framework technologies are not available in .NET Core, and some may never be available. 

  • Learning curve

.NET is extensive and has a large set of tools and technologies, which can make it challenging for new developers to learn. 

  • Legacy

Many CMS and eCommerce solutions are still based on a non-Core version of .NET. 

Continue Reading →

Dependency Injection in Dotnet Core

 Dependency Injection (DI) in .NET Core is a fundamental design pattern that allows objects or services to be passed (injected) into a class rather than the class creating those dependencies itself. This promotes loose coupling and enhances testability and maintainability. .NET Core has built-in support for Dependency Injection via the Microsoft.Extensions.DependencyInjection library.

Key Concepts of Dependency Injection

  1. Service: A service is any class or object that provides some functionality to the application (e.g., database access, logging, or business logic).

  2. Dependency Injection Container: A DI container is responsible for managing the lifecycle of objects and their dependencies. It provides the necessary services and manages how objects are instantiated and injected.

  3. Injection Types:

    • Constructor Injection: Dependencies are provided via the constructor.
    • Property Injection: Dependencies are provided via properties (less common in .NET Core).
    • Method Injection: Dependencies are passed through method parameters.
  4. Lifetime of Services:

    • Transient: A new instance of the service is created each time it is requested.
    • Scoped: A single instance of the service is created per HTTP request, meaning it is shared within the scope of a request.
    • Singleton: A single instance of the service is created and shared throughout the application's lifetime.

How Dependency Injection Works in .NET Core

Step 1: Define Services/Interfaces

Create the interfaces and classes that define the services you want to inject.

public interface IWeatherService
{
    string GetWeather();
}

public class WeatherService : IWeatherService
{
    public string GetWeather()
    {
        return "Sunny";
    }
}

Step 2: Register Services with the DI Container

In .NET Core, services are registered in the ConfigureServices method of Startup.cs or Program.cs. This method adds the services to the DI container, specifying their lifetime. Learn here also

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Register services with different lifetimes
        services.AddTransient<IWeatherService, WeatherService>(); // Transient
        // You can also use services.AddScoped<IWeatherService, WeatherService>();
        // Or services.AddSingleton<IWeatherService, WeatherService>();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // Normal middleware pipeline setup
    }
}
  • AddTransient<TService, TImplementation>: Registers a service with a transient lifetime, meaning a new instance is created each time the service is requested.
  • AddScoped<TService, TImplementation>: Registers a service with a scoped lifetime, meaning the service is created once per HTTP request.
  • AddSingleton<TService, TImplementation>: Registers a service with a singleton lifetime, meaning a single instance is used throughout the application's lifetime.

Step 3: Inject Dependencies into Controllers or Services

In ASP.NET Core, dependencies are injected via constructor injection. The framework automatically resolves dependencies by looking at the constructor parameters and providing the appropriate instances from the DI container.

public class WeatherController : ControllerBase
{
    private readonly IWeatherService _weatherService;

    // Constructor Injection
    public WeatherController(IWeatherService weatherService)
    {
        _weatherService = weatherService;
    }

    public IActionResult GetWeather()
    {
        var weather = _weatherService.GetWeather();
        return Ok(weather);
    }
}

In this example, the IWeatherService dependency is injected into the WeatherController. ASP.NET Core automatically provides an instance of WeatherService because it was registered in the DI container.

Step 4: Using DI in Other Classes

You can inject services into any class that the DI container manages, not just controllers. For instance, you might inject a service into a background task or a custom service class.

public class MyService
{
    private readonly IWeatherService _weatherService;

    public MyService(IWeatherService weatherService)
    {
        _weatherService = weatherService;
    }

    public void PerformTask()
    {
        var weather = _weatherService.GetWeather();
        // Do something with the weather data
    }
}

Step 5: Resolving Dependencies at Runtime

When you request a service via DI, you can resolve it in two ways:

  1. Constructor Injection: As shown in the examples above, the DI container will automatically provide dependencies when the class is instantiated.
  2. Manually Resolving a Service: You can manually resolve a service from the DI container using the IServiceProvider interface. This is common in scenarios like background services or factory patterns.
public class MyService
{
    private readonly IServiceProvider _serviceProvider;

    public MyService(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public void ExecuteTask()
    {
        var weatherService = _serviceProvider.GetRequiredService<IWeatherService>();
        var weather = weatherService.GetWeather();
    }
}

Dependency Injection is handled by the built-in IoC container, which resolves services based on their lifetime and dependencies. This is typically done via constructor injection, where the necessary services are injected automatically by the framework. 

Benefits of Dependency Injection

  • Loose Coupling: Classes don’t manage their own dependencies, making it easier to swap out services.
  • Testability: You can inject mock services for unit testing without needing to change the class.
  • Flexibility: You can configure different lifetimes (transient, scoped, singleton) to manage resource usage and object creation.
  • Separation of Concerns: Classes focus on their primary responsibility, delegating the management of dependencies to the DI container.

Common Issues and Best Practices

  • Circular Dependencies: Be cautious of circular dependencies (A depends on B, and B depends on A). These can cause problems and are generally considered poor design.
  • Overusing DI: Don't overuse DI in situations where it’s not necessary. Sometimes, having a clear, explicit dependency in your class constructor is fine without the need for DI.
  • Single Responsibility: Ensure that services have a single responsibility, and avoid placing too many responsibilities within a single service class. This helps in maintaining code that is easier to understand and test.

Conclusion

In .NET Core, Dependency Injection is a powerful pattern that promotes loose coupling, testability, and maintainability. The framework provides built-in DI support that allows you to register, resolve, and manage dependencies in a very straightforward way. By leveraging DI properly, you can write more modular, maintainable, and scalable applications.


Continue Reading →

Saturday, 17 August 2024

Entity Framework Core

Entity Framework Core (EF Core) is an open-source, lightweight, and extensible Object-Relational Mapper (ORM) developed by Microsoft. It is designed to work with .NET applications to facilitate data access and manipulation using object-oriented programming concepts.

Here are some key features and concepts of EF Core:

  1. Object-Relational Mapping (ORM): EF Core helps in mapping .NET objects to database tables, allowing developers to interact with a database using strongly-typed C# classes rather than writing raw SQL queries.

  2. Database Providers: EF Core supports a variety of database systems through different database providers, including Microsoft SQL Server, SQLite, PostgreSQL, MySQL, and more. Each provider contains the necessary implementation for working with a specific type of database.

  3. LINQ Queries: EF Core allows developers to write queries using Language Integrated Query (LINQ), which is then translated into the appropriate SQL queries by the framework.

  4. Migrations: EF Core provides a migrations feature that helps manage database schema changes over time. It allows developers to create, modify, and update database schemas in a controlled manner.

  5. Change Tracking: EF Core tracks changes made to entities and automatically generates the necessary SQL commands to update the database when SaveChanges is called.

  6. Caching and Performance: EF Core includes various performance optimization features, such as caching and lazy loading, to improve the efficiency of data access operations.

  7. NoSQL Support: Although EF Core is primarily used with relational databases, it also has some support for NoSQL databases, particularly through custom providers and extensions.

  8. Cross-Platform: EF Core is cross-platform and can be used with .NET Core, making it suitable for developing applications that run on different operating systems, including Windows, Linux, and macOS.

Difference between entity framework and entity framework coreClick here

EF Core is part of the larger .NET ecosystem and is commonly used in ASP.NET Core applications to handle data access. It provides a high-level, abstracted way to interact with databases, allowing developers to focus more on business logic rather than database-related concerns.

EF Core Database First Approach
Sometimes we may have an existing database. When we have a database and the database tables already, we use the database first approach. With the database first approach, EF Core creates the DBContext and Domain classes based on the existing database schema.

EF Core Database Providers
EF Core supports many relational and even non relational databases. EF Core is able to do this by using plug-in libraries called the database providers. These database providers are available as NuGet packages. 

List of EF Core Database Providers

https://docs.microsoft.com/en-us/ef/core/providers/

A database provider, usually sits between EF Core and the database it supports. The database provider contains the functionality specific to the database it supports. Functionality that is common to all the databases is in the EF Core component. Functionality that is specific to a database, for example, Microsoft SQL Server specific functionality is with-in the SQL Server provider for EF Core. 

To install Entity Framework Core and to be able to use SQL server as the database for your application, you need to install the following nuget packages.

Microsoft.EntityFrameworkCore.SqlServer - This nuget package contains SQL Server specific functionality

Microsoft.EntityFrameworkCore.Relational - This nuget package contains functionality that is common to all relational databases

Microsoft.EntityFrameworkCore - This nuget package contains common entity frameowrk core functionality

When we install Microsoft.EntityFrameworkCore.SqlServer package, it also installs all the other dependant nuget packages automatically. 

DbContext in entity framework core

One of the very important classes in Entity Framework Core is the DbContext class. This is the class that we use in our application code to interact with the underlying database. It is this class that manages the database connection and is used to retrieve and save data in the database.

To use the DbContext class in our application We create a class that derives from the DbContext class.
DbContext class is in Microsoft.EntityFrameworkCore namespace.

public class AppDbContext : DbContext
{ }


For the DbContext class to be able to do any useful work, it needs an instance of the DbContextOptions class.
 The DbContextOptions instance carries configuration information such as the connection string, database provider to use etc.
To pass the DbContextOptions instance we use the constructor as shown in the example below.

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions[AppDbContextoptions)
        : base(options)
    {
    }
    public DbSet[EmployeeEmployees { getset; }
}


The DbContext class includes a DbSet[TEntity] property for each entity in the model.

Using sql server with entity framework core
When using Entity Framework Core, one of the important things that we need to configure is the database provider that we plan to use.  Click here

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContextPool[AppDbContext](options =>
      options.UseSqlServer(_config.GetConnectionString("EmployeeDBConnection")));

    services.AddMvc().AddXmlSerializerFormatters();
    services.AddTransient[IEmployeeRepositoryMockEmployeeRepository]();
}


We want to configure and use Microsoft SQL Server with entity framework core. We usually specify this configuration in ConfigureServices() method in Startup.cs file.

We can use either AddDbContext() or AddDbContextPool() method to register our application specific DbContext class with the ASP.NET Core dependency injection system.

The difference between AddDbContext() and AddDbContextPool() methods is, AddDbContextPool() method provides DbContext pooling.

With DbContext pooling, an instance from the DbContext pool is provided if available, rather than creating a new instance.

DbContext pooling is conceptually similar to how connection pooling works in ADO.NET.

From a performance standpoint AddDbContextPool() method is better over AddDbContext() method.

UseSqlServer() extension method is used to configure our application specific DbContext class to use Microsoft SQL Server as the database.

To connect to a database, we need the database connection string which is provided as a parameter to UseSqlServer() extension method

Instead of hard-coding the connection string in application code, we store it appsettings.json configuration file.

{
    "ConnectionStrings": {
      "EmployeeDBConnection": "server=(localdb)\\MSSQLLocalDB;database=EmployeeDB;
Trusted_Connection=true"
    }
  }


To read connection string from appsettings.json file we use IConfiguration service GetConnectionString() method.

Entity framework core migrations- Click hereClick hereClick here

Migration is an entity framework core feature that keeps the database schema and our application model classes (also called entity class) in sync.

If you have not executed at-least the initial migration in your application you might get the following SqlException

SqlException: Cannot open database "EmployeeDB" requested by the login.

This is because we do not have the database created yet. One way to create the database is by 

  • Creating a migration first and then
  • Executing that migration

We will be using the following commands to work with migrations in entity framework core.

Add-Migration: Adds a new migration
Update-Database: Updates the database to a specified migration
Remove-Migration: It only removes one migration at a time and that too only the latest migration that is not yet applied to the database. If all the migrations are already applied, executing Remove-Migration command throws the following exception.

Creating a Migration in Entity Framework Core
The following command creates the initial migration. InitialCreate is the name of the migration.

Add-Migration InitialCreate


When the above command completes, you will see a file in the "Migrations" folder that contains the name InitialCreate.cs. This file has the code required to create the respective database tables.

Update-Database in Entity Framework Core
We need to execute the migration code to create the tables. If the database does not exist already, it creates the database and then the database tables. For updating the database, we use Update-Database command. To the Update-Database command we may pass the migration name we want to execute. If no migration is specified, the command by default executes the last migration.

Entity framework core seed data Click here
If you are using Entity Framework Core 2.1 or later there is a new method of seeding database data. In your application DbContext class, override OnModelCreating() method.

HasData() method configures entity to have the specified seed data.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity[Employee]().HasData(
        new Employee
        {
            Id = 1,
            Name = "Mark",
            Department = Dept.IT,
            Email = "mark@pragimtech.com"
        }
    );
}


EF CORE Simple project https://www.tektutorialshub.com/

Continue Reading →

Wednesday, 2 August 2023

Dotnet Core Versions

.NET Core is a cross-platform, open-source framework developed by Microsoft for building modern, scalable, and high-performance applications. It has since been unified with .NET Framework into a single product under the name ".NET" (starting with version 5), which is a continuation of .NET Core.

Here’s a summary of the evolution and versions of .NET Core:

  1. .NET Core 1.0 - Released in June 2016.
  2. .NET Core 1.1 - Released in November 2016.
  3. .NET Core 2.0 - Released in August 2017.
  4. .NET Core 2.1 - Released in May 2018 (LTS).
  5. .NET Core 2.2 - Released in December 2018.
  6. .NET Core 3.0 - Released in September 2019.
  7. .NET Core 3.1 - Released in December 2019 (LTS).

After .NET Core 3.1, the versioning transitioned to .NET 5:

  1. .NET 5 - Released in November 2020 (marks the unification of .NET Core and .NET Framework).
  2. .NET 6 - Released in November 2021 (LTS).
  3. .NET 7 - Released in November 2022.
  4. .NET 8 - Released in November 2023 (LTS).

The versioning structure now focuses on just ".NET", where .NET Core versions are no longer distinct, and the term ".NET Core" has been replaced by ".NET". .NET 5 and onwards represent the unified platform that evolved from .NET Core.

To check the version of .NET (whether .NET Core or the latest .NET versions), you can use the command:

dotnet --version

Continue Reading →

Sunday, 22 January 2023

JWT authentication in ASP.NET Core WebAPI

Using JWT (JSON Web Tokens) in a Web API is a common approach for handling authentication and authorization. Here's a concise guide on how to implement JWT in a Web API, typically using a framework like ASP.NET Core, but the principles apply to other frameworks as well.

Step 1: Install Necessary Packages

For ASP.NET Core, you'll need to install the following NuGet packages:

  1. Microsoft.AspNetCore.Authentication.JwtBearer
  2. System.IdentityModel.Tokens.Jwt

Step 2: Configure JWT in Startup

In your Startup.cs file, configure JWT authentication in the ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    // Other service configurations...

    var key = Encoding.ASCII.GetBytes("your_secret_key_here"); // Use a strong secret key
    services.AddAuthentication(x =>
    {
        x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(x =>
    {
        x.RequireHttpsMetadata = false; // Set to true in production
        x.SaveToken = true;
        x.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = false,
            ValidateAudience = false
        };
    });

    services.AddControllers();
}

Step 3: Create a JWT Token

You'll need a method to generate the JWT. This typically occurs during login:

  public string GenerateJwtToken(string username)
  {
// Define JWT claims
      var claims = new[]
      {
          new Claim(JwtRegisteredClaimNames.Sub, userid), // Registered Claims
new Claim(JwtRegisteredClaimNames.Name, username), // Registered Claims
          new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim("role", "admin"), // Custom Claims
new Claim("email", "johndoe@example.com") // Custom Claims
      };
 
// Define the security key
string secretKey = "your_secret_key_here";
      var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));

// Define the signing credentials (HMACSHA256 algorithm)
      var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
 
      var token = new JwtSecurityToken(
          issuer: "your-issuer", // Can be your app name
          audience: "your-audience", // Can be a target application or service
          claims: claims,
          expires: DateTime.Now.AddMinutes(30),
          signingCredentials: creds);
 
       // Serialize the token to a string
       var tokenHandler = new JwtSecurityTokenHandler();
       string jwtToken = tokenHandler.WriteToken(token);

      return jwtToken ;
  }

Step 4: Secure Your API Endpoints

Use the [Authorize] attribute to protect your API endpoints:

  [Authorize]
  [ApiController]
  [Route("[controller]")]
  public class WeatherForecastController : ControllerBase
  {
      [HttpGet]
      public IActionResult Get()
      {
          return Ok(new { Message = "This is a protected endpoint!" });
      }
  }

Step 5: Handling User Login

Create a login endpoint to authenticate users and return a JWT:

  [HttpPost("login")]
  public IActionResult Login([FromBody] LoginModel login)
  {
      // Validate user credentials (this is just an example)
      if (login.Username == "test" && login.Password == "password") // Replace with actual validation
      {
          var token = GenerateJwtToken(login.Username);
          return Ok(new { Token = token });
      }
 
      return Unauthorized();
  }

Step 6: Testing

Use a tool like Postman to test your endpoints:

  1. Call the login endpoint with valid credentials to receive a JWT.
  2. Use the received token in the Authorization header (Bearer <token>) when accessing protected endpoints.

Where jwt tokens are stored on on server

JWT (JSON Web Tokens) are typically not stored on the server in the same way as session data. Instead, they are often used in a stateless manner, meaning the server does not maintain a session for each user. Here’s how it generally works:

  1. Client-Side Storage: After authentication, the server sends the JWT to the client, which usually stores it in local storage or cookies.

  2. Stateless Authentication: Each time the client makes a request, it sends the JWT along (typically in the Authorization header). The server validates the token without needing to store any session data.

  3. Optional Revocation: If you need to implement token revocation or blacklisting, you might maintain a list of revoked tokens on the server, but this is an additional layer of complexity that somewhat counters the stateless principle.

  4. Expiry: JWTs usually have an expiration time, after which they are considered invalid. This reduces the need for server-side storage since expired tokens can be discarded.

In summary, JWTs are mainly stored client-side, while the server verifies them as needed.

How server verifies jwt token on server

To verify a JWT (JSON Web Token) on the server, the following steps are typically followed:

  1. Extract the Token: The server retrieves the JWT from the request, usually from the Authorization header as a Bearer token.

  2. Decode the Token: The server decodes the JWT to access its header and payload. This step does not require validation and can be done using a base64 decoding method.

  3. Verify the Signature: The most critical part of the verification process is to check the signature of the token:

    • The server uses the algorithm specified in the JWT header (e.g., HS256, RS256) and the secret key (for symmetric algorithms) or the public key (for asymmetric algorithms) that was used to sign the token.
    • It re-generates the signature using the header and payload and compares it with the signature part of the received token.
  4. Check Claims: The server validates the claims in the payload:

    • Expiration: Check the exp claim to see if the token is still valid.
    • Audience: Verify the aud claim to ensure the token was intended for your server.
    • Issuer: Check the iss claim to confirm it was issued by a trusted source.
    • Not Before: Optionally, check the nbf claim to see if the token is being used before its valid time.
  5. Process the Request: If the token is valid and all claims check out, the server processes the request. If not, it responds with an appropriate error (e.g., 401 Unauthorized).

Access token vs Refresh Token:

  1. Access Token (short-lived): This token is used for authenticating requests and is typically valid for a short duration (e.g., 15 minutes).
  2. Refresh Token (long-lived): This token is used to get a new access token when the old one expires. It typically has a longer expiry time (e.g., 7 days or more). 
What information JWT token contains

JWT Token Generation Code in C#
Click here

Claim in jwt authentication token
Click here

By following these steps, the server ensures that the JWT is valid, has not been tampered with, and is still active.


Reference: https://medium.com/https://www.c-sharpcorner.com/https://javascript.plainenglish.io/

Continue Reading →

Wednesday, 4 January 2023

Sessions and Caching In ASP.NET Core

 How To Use Sessions In ASP.NET Core

1- We need to install the stable version of “Microsoft.AspNetCore.Session” from the NuGet Package Manager. Then only we can access the session state in ASP.NET Core.

2- Now, open the ”Startup.cs” to configure the services.  we need to add the session service to the container so that we can add the services in the “ConfigureServices” function.

public void ConfigureServices(IServiceCollection services)  
{
    services.AddDistributedMemoryCache();  
    services.AddSession(options => {  
        options.IdleTimeout = TimeSpan.FromMinutes(1); //Set Time  
    });  
    services.AddMvc();  
}

3- Configure the HTTP Request Pipeline

Now, in the same class, we add “app.UseSession()” inside the “Configure” function so that it gets called by the runtime.

app.UseSession();

Now we are ok to use session in our application. See the below code for session.

public class HomeController : Controller  
{  
    const string SessionName = "_Name";  
    const string SessionAge = "_Age";  
    public IActionResult Index()  
    {  
        HttpContext.Session.SetString(SessionName, "Jarvik");  
        HttpContext.Session.SetInt32(SessionAge, 24);  
        return View();  
    }  

    public IActionResult About()  
    {  
        ViewBag.Name = HttpContext.Session.GetString(SessionName);  
        ViewBag.Age = HttpContext.Session.GetInt32(SessionAge);  
        ViewData["Message"] = "Asp.Net Core !!!.";  

        return View();  
    }  
}

Cache in ASP.NET Core

ASP.NET Core supports several different caches. The simplest cache is based on the IMemoryCache. IMemoryCache represents a cache stored in the memory of the web server. Apps running on a server farm (multiple servers) should ensure sessions are sticky when using the in-memory cache. Sticky sessions ensure that requests from a client all go to the same server. 

Non-sticky sessions in a web farm require a distributed cache to avoid cache consistency problems. 

The in-memory cache can store any object. The distributed cache interface is limited to byte[]. The in-memory and distributed cache store cache items as key-value pairs.

Types of Caching in Dotnet Core: 

The lowest level of caching in ASP.NET Core that we are going to discuss is the caching of data using IMemoryCache and IDistributedCache. These interfaces are the standard, in-built mechanisms for caching data in .NET Core. All other techniques that we discuss later in the article rely on IMemoryCache or IDistributedCache internally.

IMemoryCache: IMemoryCache is very similar to the System.Runtime.Caching.MemoryCache cache from .NET 4.

You can register IMemoryCache in ConfigureServices using:

services.AddMemoryCache();

//services.AddDistributedMemoryCache();
//services.AddResponseCaching();

Implementing MemoryCache in Code.

public class BlahService
{
    private const string BlahCacheKey = "blah-cache-key";
    private readonly IMemoryCache _cache;

    public BlahService(IMemoryCache cache, IDatabase db)
    {
        _cache = cache;
    }
   
    public async Task<IEnumerable<Blah>> GetBlahs()
    {
        blahs = await _db.getAll<Blah>(...);
        _cache.Set(BlahCacheKey, blahs, ...);
        return blahs;
    }
}

When saving to IMemoryCache, MemoryCacheEntryOptions provides you with many ways to expire cache content. 

//absolute expiration using TimeSpan
_cache.Set("key", item, TimeSpan.FromDays(1));

//absolute expiration using DateTime
_cache.Set("key", item, new DateTime(2020, 1, 1));

//sliding expiration (evict if not accessed for 7 days)
_cache.Set("key", item, new MemoryCacheEntryOptions
{
    SlidingExpiration = TimeSpan.FromDays(7)
});

Learn more about Memory Cache https://learn.microsoft.com

IDistributedCache A distributed cache is a cache shared by multiple app servers, typically maintained as an
external service to the app servers that access it. A distributed cache can improve the performance
and scalability of an ASP.NET Core app, especially when the app is hosted by a cloud service
or a server farm.
A distributed cache has several advantages over other caching scenarios where cached data is
stored on individual app servers.
When cached data is distributed, the data:
  1. Is coherent (consistent) across requests to multiple servers.
  2. Survives server restarts and app deployments.
  3. Doesn't use local memory.
Distributed cache configuration is implementation specific. This article describes how to configure
SQL Server and Redis distributed caches. Third party implementations are also available, such as
NCache (NCache on GitHub). Regardless of which implementation is selected, the app interacts with
the cache using the IDistributedCache interface.

Learn More about distributed cache


Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives