Md Mominul Islam | Software and Data Enginnering | SQL Server, .NET, Power BI, Azure Blog

while(!(succeed=try()));

LinkedIn Portfolio Banner

Latest

Home Top Ad

Responsive Ads Here

Post Top Ad

Responsive Ads Here

Thursday, September 4, 2025

Ultimate ASP.NET Full Course: Module 7 - Advanced Development, AI Tools & Performance

 

Table of Contents

  1. Module 7: Advanced Development, AI Tools & Performance

    • 1.1 Framework Features

      • Filters (Action, Exception, Result)

      • Caching (In-Memory, Redis, Response)

      • Background Services (IHostedService, Hangfire)

    • 1.2 AI-Powered Development

      • GitHub Copilot & VS IntelliCode for Faster Coding

      • Azure OpenAI & ChatGPT for Architecture Design, Code Snippets, Testing

      • AI-Enhanced Debugging, Recommendations, Code Review Tools

    • 1.3 Performance & Health

      • Async Programming Best Practices

      • Response Compression, Health Checks

      • Logging & Monitoring (Serilog, NLog, Application Insights)

    • 1.4 Lab: Add Redis Cache + Background Queue Service + Use Copilot to Generate/Test a Class

      • Real-Life Example: E-Commerce Product Recommendation System

      • Step-by-Step Code Implementation

      • Best Practices, Exception Handling, Pros/Cons, Alternatives


Introduction

Welcome to Module 7 of the Ultimate ASP.NET Full Course (2025 Edition)! This module focuses on advanced ASP.NET Core development, leveraging powerful framework features, integrating AI-powered tools, and optimizing application performance. You'll master filters for cross-cutting concerns, caching for speed, and background services for long-running tasks. We'll explore AI tools like GitHub Copilot, Visual Studio IntelliCode, and Azure OpenAI to accelerate coding, design architectures, and enhance debugging. Performance techniques include async programming, compression, health checks, and monitoring with tools like Serilog and Application Insights.

Using a real-life e-commerce scenario—building a product recommendation system with caching and background processing—this guide is step-by-step, code-heavy, and user-friendly. It includes best practices, exception handling, pros/cons, and alternatives. The lab will have you implementing Redis caching, a Hangfire background queue, and using Copilot to generate and test a recommendation class.

By the end, you'll be ready to build high-performance, AI-enhanced applications. Let's dive into advanced .NET development!


1.1 Framework Features

Filters (Action, Exception, Result)

Filters in ASP.NET Core enable cross-cutting concerns like logging, authorization, or exception handling.

  • Action Filters: Run before/after action execution.

    • Example: Log action execution time.

      public class LogActionFilter : IActionFilter
      {
          public void OnActionExecuting(ActionExecutingContext context)
          {
              context.HttpContext.Items["StartTime"] = DateTime.UtcNow;
          }
      
          public void OnActionExecuted(ActionExecutedContext context)
          {
              var startTime = (DateTime)context.HttpContext.Items["StartTime"];
              var duration = DateTime.UtcNow - startTime;
              Console.WriteLine($"Action {context.ActionDescriptor.DisplayName} took {duration.TotalMilliseconds}ms");
          }
      }
    • Register: builder.Services.AddControllers(options => options.Filters.Add<LogActionFilter>());

  • Exception Filters: Handle errors globally.

    • Example: Custom error response.

      public class CustomExceptionFilter : IExceptionFilter
      {
          public void OnException(ExceptionContext context)
          {
              context.Result = new ObjectResult(new { error = context.Exception.Message })
              {
                  StatusCode = 500
              };
              context.ExceptionHandled = true;
          }
      }
  • Result Filters: Modify action results.

    • Example: Add custom headers.

      public class CustomResultFilter : IResultFilter
      {
          public void OnResultExecuting(ResultExecutingContext context)
          {
              context.HttpContext.Response.Headers.Add("X-Custom-Header", "Value");
          }
      
          public void OnResultExecuted(ResultExecutedContext context) { }
      }

Real-Life Analogy: Filters are like airport security checkpoints—Action checks bags, Exception handles issues, Result adds tags.

Real-Life Example: E-commerce app logs API calls (Action), returns user-friendly errors (Exception), and adds cache headers (Result).

Best Practices:

  • Use filters for cross-cutting concerns, not business logic.

  • Register globally or per controller/action with [TypeFilter].

Exception Handling:

  • Log exceptions in filters.

  • Use IExceptionFilter for specific error types.

Pros:

  • Reusable, modular logic.

  • Simplifies controller code.

Cons:

  • Overuse can clutter pipeline.

  • Order matters (configure carefully).

Alternatives:

  • Middleware: For request-level concerns.

  • AOP Libraries: PostSharp for advanced aspects.

Expanding on Filters: Filters can be synchronous or async (IAsyncActionFilter). Scoped filters use DI for services like loggers. In .NET 9, filters support endpoint metadata for minimal APIs. Realistics: High-traffic e-commerce uses filters for rate limiting. Pros: Clean separation; cons: Debugging complex filter chains.


1.2 Caching (In-Memory, Redis, Response)

Caching improves performance by storing frequently accessed data.

  • In-Memory Caching: Built-in, stores data in server memory.

    • Setup: builder.Services.AddMemoryCache();

    • Example:

      public class ProductService
      {
          private readonly IMemoryCache _cache;
      
          public ProductService(IMemoryCache cache)
          {
              _cache = cache;
          }
      
          public async Task<Product> GetProductAsync(int id)
          {
              string cacheKey = $"Product_{id}";
              if (!_cache.TryGetValue(cacheKey, out Product product))
              {
                  product = await FetchFromDbAsync(id); // Simulated DB call
                  _cache.Set(cacheKey, product, TimeSpan.FromMinutes(10));
              }
              return product;
          }
      }
  • Redis Caching: Distributed cache for scalability.

    • NuGet: Microsoft.Extensions.Caching.StackExchangeRedis

    • Setup:

      builder.Services.AddStackExchangeRedisCache(options =>
      {
          options.Configuration = builder.Configuration.GetConnectionString("Redis");
          options.InstanceName = "ProductCache_";
      });
    • Usage: Same as in-memory but distributed.

  • Response Caching: Cache HTTP responses.

    • Setup: builder.Services.AddResponseCaching(); app.UseResponseCaching();

    • Example:

      [ResponseCache(Duration = 60, Location = ResponseCacheLocation.Any)]
      [HttpGet("products")]
      public IActionResult GetProducts()
      {
          return Ok(GetProductsFromDb());
      }

Real-Life Analogy: Caching is a fridge—In-Memory for quick snacks, Redis for shared groceries, Response for pre-cooked meals.

Real-Life Example: E-commerce caches product details (Redis) and category lists (Response) to reduce DB load.

Best Practices:

  • Use sliding expiration for in-memory.

  • Secure Redis with SSL.

  • Vary response cache by headers/query.

Exception Handling:

  • Handle cache misses gracefully.

  • Log Redis connection failures.

Pros:

  • Significant performance boost.

  • Redis scales across servers.

Cons:

  • Stale data risks.

  • Redis setup complexity.

Alternatives:

  • Memcached: Alternative distributed cache.

  • Output Caching Middleware: .NET 7+ feature.

Details: .NET 9 improves output caching with custom policies. Realistics: Amazon uses Redis for product caching. Pros: Reduces latency; cons: Cache invalidation challenges.


1.3 Background Services (IHostedService, Hangfire)

Background services handle long-running tasks outside the request pipeline.

  • IHostedService: Built-in for custom services.

    • Example: Periodic data cleanup.

      public class CleanupService : BackgroundService
      {
          protected override async Task ExecuteAsync(CancellationToken stoppingToken)
          {
              while (!stoppingToken.IsCancellationRequested)
              {
                  // Cleanup logic
                  await Task.Delay(TimeSpan.FromHours(1), stoppingToken);
              }
          }
      }
    • Register: builder.Services.AddHostedService<CleanupService>();

  • Hangfire: NuGet Hangfire.AspNetCore, Hangfire.SqlServer.

    • Setup:

      builder.Services.AddHangfire(config => config.UseSqlServerStorage(builder.Configuration.GetConnectionString("Hangfire")));
      app.UseHangfireDashboard();
      app.UseHangfireServer();
    • Schedule job:

      BackgroundJob.Enqueue(() => ProcessRecommendations());

Real-Life Analogy: Background services are like kitchen staff—cleaning (IHostedService) or handling bulk orders (Hangfire).

Real-Life Example: E-commerce schedules recommendation updates with Hangfire.

Best Practices:

  • Use IHostedService for simple tasks.

  • Monitor Hangfire jobs via dashboard.

Exception Handling:

  • Log failures in background tasks.

  • Retry policies in Hangfire.

Pros:

  • Decouples tasks from requests.

  • Hangfire’s dashboard for monitoring.

Cons:

  • Resource-intensive if mismanaged.

Alternatives:

  • Quartz.NET: Job scheduling.

  • Azure Functions: Serverless.

Expand: .NET 9 enhances IHostedService with graceful shutdown. Realistics: Background jobs for email notifications.


1.4 AI-Powered Development

GitHub Copilot & VS IntelliCode for Faster Coding

AI tools accelerate development.

  • GitHub Copilot: Suggests code completions in VS/VS Code.

    • Example: Type // Calculate product discount and Copilot suggests:

      public decimal CalculateDiscount(Product product, decimal rate)
      {
          return product.Price * rate;
      }
    • Use: Enable in VS Code or Visual Studio 2022.

  • VS IntelliCode: Context-aware suggestions.

    • Example: Suggests common LINQ patterns.

Real-Life Example: Copilot generates boilerplate for product services; IntelliCode refines LINQ queries.

Azure OpenAI & ChatGPT for Architecture Design, Code Snippets, Testing

  • Azure OpenAI: Integrate via SDK for code generation, testing.

    • Example: Generate unit test.

      [Fact]
      public void CalculateDiscount_ReturnsCorrectValue()
      {
          var product = new Product { Price = 100 };
          var service = new ProductService();
          var result = service.CalculateDiscount(product, 0.1m);
          Assert.Equal(10m, result);
      }
  • ChatGPT: Prompt for architecture advice, e.g., “Design a microservices pattern for e-commerce.”

Real-Life Example: Use Azure OpenAI to suggest caching strategies.

AI-Enhanced Debugging, Recommendations, Code Review Tools

  • Debugging: Copilot suggests fixes for exceptions.

  • Recommendations: IntelliCode flags anti-patterns.

  • Code Review: AI tools highlight maintainability issues.

Best Practices:

  • Validate AI-generated code.

  • Combine with manual review.

Exception Handling:

  • Handle AI misinterpretations manually.

Pros:

  • Speeds up coding.

  • Reduces boilerplate.

Cons:

  • May suggest incorrect code.

  • Dependency on external services.

Alternatives:

  • CodeRush: Non-AI tooling.

  • Manual Analysis: Traditional reviews.

Expand: Azure OpenAI integrates with CI/CD for automated testing. Realistics: Startups use Copilot for rapid prototyping.


1.5 Performance & Health

Async Programming Best Practices

  • Use async/await for I/O-bound operations.

    public async Task<Product> GetProductAsync(int id)
    {
        return await _context.Products.FindAsync(id);
    }
  • Avoid blocking: Use await instead of .Result.

Response Compression, Health Checks

  • Compression: builder.Services.AddResponseCompression(); app.UseResponseCompression();

  • Health Checks: Monitor app status.

    builder.Services.AddHealthChecks();
    app.MapHealthChecks("/health");

Logging & Monitoring (Serilog, NLog, Application Insights)

  • Serilog: NuGet Serilog.AspNetCore.

    builder.Host.UseSerilog((ctx, lc) => lc.WriteTo.Console().WriteTo.File("logs/app.log"));
  • Application Insights: Azure monitoring.

    builder.Services.AddApplicationInsightsTelemetry();

Real-Life Example: E-commerce logs API calls, monitors health for uptime.

Best Practices:

  • Use async I/O.

  • Structured logging with Serilog.

Exception Handling:

  • Log unhandled exceptions.

Pros:

  • Scalable async apps.

  • Comprehensive monitoring.

Cons:

  • Async debugging complexity.

Alternatives:

  • NLog: Alternative logger.

  • Prometheus: Open-source monitoring.

Expand: .NET 9 improves async diagnostics. Realistics: Netflix uses similar monitoring.


1.6 Lab: Add Redis Cache + Background Queue Service + Use Copilot to Generate/Test a Class

Real-Life Example: E-Commerce Product Recommendation System

Build an API with Redis caching, Hangfire for background recommendation processing, and use Copilot to generate/test a recommendation class.

Step-by-Step

  1. Setup: dotnet new webapi -n ProductApi.

  2. Redis: Add caching for products.

  3. Hangfire: Schedule recommendation jobs.

  4. Copilot: Generate/test RecommendationService.

Code Example

Program.cs

builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = builder.Configuration.GetConnectionString("Redis");
});
builder.Services.AddHangfire(config => config.UseSqlServerStorage(builder.Configuration.GetConnectionString("Hangfire")));
builder.Services.AddApplicationInsightsTelemetry();
app.UseHangfireDashboard();
app.UseHangfireServer();

RecommendationService.cs (Copilot-Generated)

public class RecommendationService
{
    private readonly IMemoryCache _cache;
    private readonly ILogger<RecommendationService> _logger;

    public RecommendationService(IMemoryCache cache, ILogger<RecommendationService> logger)
    {
        _cache = cache;
        _logger = logger;
    }

    public async Task<List<Product>> GetRecommendationsAsync(int userId)
    {
        string cacheKey = $"Recommendations_{userId}";
        if (!_cache.TryGetValue(cacheKey, out List<Product> recommendations))
        {
            recommendations = await GenerateRecommendationsAsync(userId);
            _cache.Set(cacheKey, recommendations, TimeSpan.FromMinutes(30));
            _logger.LogInformation("Generated recommendations for user {UserId}", userId);
        }
        return recommendations;
    }

    private async Task<List<Product>> GenerateRecommendationsAsync(int userId)
    {
        // Simulated DB call
        return new List<Product> { new Product { Id = 1, Name = "Laptop" } };
    }
}

Unit Test (Copilot-Generated)

public class RecommendationServiceTests
{
    [Fact]
    public async Task GetRecommendationsAsync_CachesResults()
    {
        var cache = new MemoryCache(new MemoryCacheOptions());
        var logger = new Logger<RecommendationService>(new LoggerFactory());
        var service = new RecommendationService(cache, logger);

        var result1 = await service.GetRecommendationsAsync(1);
        var result2 = await service.GetRecommendationsAsync(1);

        Assert.Same(result1, result2); // Cached
    }
}

How to Run

  • Setup Redis, Hangfire, run API.

  • Use Copilot to generate/test code.

  • Monitor with Application Insights.

Explanation/Best Practices/etc.

  • Cached recommendations, queued jobs, AI-assisted coding.

No comments:

Post a Comment

Thanks for your valuable comment...........
Md. Mominul Islam

Post Bottom Ad

Responsive Ads Here