<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Gaurav</title>
    <description>The latest articles on Forem by Gaurav (@gaurav-nandankar).</description>
    <link>https://forem.com/gaurav-nandankar</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1786010%2Fe27ca9d9-276d-4ffc-9ba0-5057043e0fa0.jpeg</url>
      <title>Forem: Gaurav</title>
      <link>https://forem.com/gaurav-nandankar</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/gaurav-nandankar"/>
    <language>en</language>
    <item>
      <title>🚀 Getting Started with RabbitMQ Pub/Sub using MassTransit in .NET</title>
      <dc:creator>Gaurav</dc:creator>
      <pubDate>Wed, 21 May 2025 15:23:26 +0000</pubDate>
      <link>https://forem.com/gaurav-nandankar/getting-started-with-rabbitmq-pubsub-using-masstransit-in-net-52m5</link>
      <guid>https://forem.com/gaurav-nandankar/getting-started-with-rabbitmq-pubsub-using-masstransit-in-net-52m5</guid>
      <description>&lt;p&gt;&lt;strong&gt;In this guide, we’ll set up a Publisher/Consumer architecture using RabbitMQ and MassTransit in .NET. We’ll cover:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Docker setup for RabbitMQ&lt;/li&gt;
&lt;li&gt;Publisher configuration in ASP.NET Core&lt;/li&gt;
&lt;li&gt;Consumer setup in a .NET Console App&lt;/li&gt;
&lt;li&gt;Sending and receiving messages&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;🐳 Step 1: Run RabbitMQ in Docker&lt;/strong&gt;&lt;br&gt;
Create a file named docker-compose.yml with the following content:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;version: '3'
services:
  rabbitmq:
    image: rabbitmq:3-management
    container_name: rabbitmq
    ports:
      - "5672:5672"
      - "15672:15672"
    environment:
      RABBITMQ_DEFAULT_USER: guest
      RABBITMQ_DEFAULT_PASS: guest
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker-compose up -d
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;✅ RabbitMQ Management UI: &lt;a href="http://localhost:15672" rel="noopener noreferrer"&gt;http://localhost:15672&lt;/a&gt;&lt;br&gt;
Username: guest&lt;br&gt;
Password: guest&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;📆 Step 2: Create the Shared Event Model&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This model will be shared between publisher and consumer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace Response.EventModel;

public class EventModel
{
    public string message { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;📨 Step 3: Setup the Publisher in ASP.NET Core&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;🔹 Add NuGet Packages&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;PackageReference Include="MassTransit" Version="8.4.1" /&amp;gt;
&amp;lt;PackageReference Include="MassTransit.RabbitMQ" Version="8.4.1" /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;🔹 Create the Publisher Class&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using MassTransit;
using Response.EventModel;

namespace TechnicianAdmin.Event;

public class Publisher
{
    private readonly IPublishEndpoint _publishEndpoint;

    public Publisher(IPublishEndpoint publishEndpoint)
    {
        _publishEndpoint = publishEndpoint;
    }

    public async Task PublishMessage()
    {
        var message = new EventModel
        {
            message = "Hey this is testing message from publisher"
        };

        await _publishEndpoint.Publish(message);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;🔹 Register MassTransit in Dependency Injection&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using MassTransit;
using TechnicianAdmin.Event;

public static class AddMassTransitConfiguration
{
    public static IServiceCollection MassTransitConfiguration(this IServiceCollection services)
    {
        services.AddTransient&amp;lt;Publisher&amp;gt;();

        services.AddMassTransit(x =&amp;gt;
        {
            x.SetKebabCaseEndpointNameFormatter();

            // Auto-discover consumers in the assembly (optional)
            x.AddConsumers(typeof(Program).Assembly);

            x.UsingRabbitMq((context, cfg) =&amp;gt;
            {
                cfg.Host("localhost", "/", h =&amp;gt;
                {
                    h.Username("guest");
                    h.Password("guest");
                });

                cfg.ConfigureEndpoints(context);
            });
        });

        return services;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;🔹 Inject and Use Publisher in Controller&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private readonly Publisher _publishEndpoint;

public Controller(Publisher publishEndpoint)
{
    _publishEndpoint = publishEndpoint;
}

[AllowAnonymous]
[HttpGet("publish-rabbitMQ-message")]
public async Task&amp;lt;IActionResult&amp;gt; SendMessage()
{
    await _publishEndpoint.PublishMessage();
    return Ok("Message sent to RabbitMQ");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;🗒️ Step 4: Setup the Consumer in a .NET Console App&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;🔹 Add NuGet Packages&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;PackageReference Include="MassTransit.RabbitMQ" Version="8.4.1" /&amp;gt;
&amp;lt;PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.5" /&amp;gt;
&amp;lt;PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="9.0.5" /&amp;gt;
&amp;lt;PackageReference Include="RabbitMQ.Client" Version="7.1.2" /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;🔹 Create the EventModel Again (or Share It via Class Library)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace Response.EventModel;

public class EventModel
{
    public string message { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;🔹 Create the Consumer&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using MassTransit;
using Response.EventModel;

namespace ConsoleApp1;

public class HelloMessageConsumer : IConsumer&amp;lt;EventModel&amp;gt;
{
    public Task Consume(ConsumeContext&amp;lt;EventModel&amp;gt; context)
    {
        Console.WriteLine($"Received message: {context.Message.message}");
        return Task.CompletedTask;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;🔹 Setup MassTransit in Program.cs&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using ConsoleApp1;
using MassTransit;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = Host.CreateDefaultBuilder(args);

builder.ConfigureServices((hostContext, services) =&amp;gt;
{
    services.AddMassTransit(x =&amp;gt;
    {
        x.AddConsumer&amp;lt;HelloMessageConsumer&amp;gt;();

        x.UsingRabbitMq((context, cfg) =&amp;gt;
        {
            cfg.Host("localhost", "/", h =&amp;gt;
            {
                h.Username("guest");
                h.Password("guest");
            });

            cfg.ReceiveEndpoint("hello-message-queue", e =&amp;gt;
            {
                e.ConfigureConsumer&amp;lt;HelloMessageConsumer&amp;gt;(context);
            });
        });
    });
});

await builder.Build().RunAsync();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;✅ Test the Flow&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Make sure RabbitMQ is running via Docker.&lt;/li&gt;
&lt;li&gt;Run the consumer app.&lt;/li&gt;
&lt;li&gt;Hit the API endpoint:GET &lt;a href="http://localhost:" rel="noopener noreferrer"&gt;http://localhost:&lt;/a&gt;/publish-rabbitMQ-message&lt;/li&gt;
&lt;li&gt;You should see output like:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;code&gt;Received message: Hey this is testing message from publisher&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;🧠 Conclusion&lt;/p&gt;

&lt;p&gt;Congrats! 🎉 You’ve successfully:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Set up RabbitMQ using Docker&lt;/li&gt;
&lt;li&gt;Published a message via ASP.NET Core&lt;/li&gt;
&lt;li&gt;Consumed it via a .NET Console App
This pattern forms the foundation of microservices-based communication using MassTransit + RabbitMQ in the .NET ecosystem.&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    <item>
      <title>Custom Middleware Extensions in .NET Core Web API</title>
      <dc:creator>Gaurav</dc:creator>
      <pubDate>Thu, 09 Jan 2025 18:09:44 +0000</pubDate>
      <link>https://forem.com/gaurav-nandankar/custom-middleware-extensions-in-net-core-web-api-4ndm</link>
      <guid>https://forem.com/gaurav-nandankar/custom-middleware-extensions-in-net-core-web-api-4ndm</guid>
      <description>&lt;p&gt;Middleware in ASP.NET Core is a powerful mechanism for intercepting HTTP requests and responses during their lifecycle. With custom middleware, developers can handle tasks such as logging, exception handling, and authorization in a structured and reusable manner. This blog post will guide you through creating and extending middleware in ASP.NET Core, leveraging extension methods for improved modularity and readability.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Middleware?
&lt;/h2&gt;

&lt;p&gt;Middleware is software injected into the request-response pipeline in ASP.NET Core applications. It processes HTTP requests as they flow through the pipeline, allowing developers to manipulate them before they reach the endpoint or after the endpoint has processed them.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why Use Custom Middleware?&lt;/strong&gt;&lt;br&gt;
Centralizes logic like logging, error handling, and security checks.&lt;br&gt;
Enhances maintainability by keeping concerns separate.&lt;br&gt;
Simplifies reusability and testing.&lt;/p&gt;

&lt;p&gt;Make sure you have the required package installed:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;dotnet add package Microsoft.Extensions.DependencyInjection.Abstractions&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Setting Up Middleware Extension Methods&lt;/strong&gt;&lt;br&gt;
We define a static class MiddlewareExtensions to house all our middleware extension methods:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace gaurav.Middleware;

public static class MiddlewareExtensions
{
    public static IApplicationBuilder UseAuthorizationMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware&amp;lt;AuthorizationMiddleware&amp;gt;();
    }

    public static IApplicationBuilder UseExceptionMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware&amp;lt;ExceptionMiddleware&amp;gt;();
    }

    public static IApplicationBuilder UseLoggingMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware&amp;lt;LoggingMiddleware&amp;gt;();
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each method is a thin wrapper around UseMiddleware, ensuring that the middleware can be registered in the startup pipeline succinctly.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 2: Building the Middleware Classes
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Authorization Middleware&lt;/strong&gt;&lt;br&gt;
This middleware handles authorization checks, ensuring that only authenticated users can access protected resources.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace gaurav.Middleware;

public class AuthorizationMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger&amp;lt;AuthorizationMiddleware&amp;gt; _logger;

    public AuthorizationMiddleware(RequestDelegate next, ILogger&amp;lt;AuthorizationMiddleware&amp;gt; logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context, ISQLORMService sqlOrmService)
    {
        _logger.LogInformation("Processing authorization...");
        // Implement authorization logic here
        await _next(context);
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Exception Middleware&lt;/strong&gt;&lt;br&gt;
This middleware provides a unified way to handle exceptions, log them, and return meaningful error responses to clients.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace gaurav.Middleware;

public class ExceptionMiddleware
{
    private readonly RequestDelegate _next;

    public ExceptionMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context, ILogger&amp;lt;ExceptionMiddleware&amp;gt; logger)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            logger.LogError($"Unhandled exception: {ex}");
            await HandleExceptionAsync(context, ex, Guid.NewGuid().ToString());
        }
    }

    private async Task HandleExceptionAsync(HttpContext context, Exception exception, string traceId)
    {
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = StatusCodes.Status500InternalServerError;

        await context.Response.WriteAsync(new
        {
            statusCode = context.Response.StatusCode,
            message = exception.Message,
            traceId
        }.ToString());
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Logging Middleware&lt;/strong&gt;&lt;br&gt;
This middleware logs incoming requests and outgoing responses, providing valuable insights into the application's operation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace gaurav.Middleware;

public class LoggingMiddleware
{
    private readonly RequestDelegate _next;

    public LoggingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context, ILogger&amp;lt;LoggingMiddleware&amp;gt; logger)
    {
        context.Request.EnableBuffering();
        logger.LogInformation($"Incoming request: {context.Request.Method} {context.Request.Path}");

        await _next(context);

        logger.LogInformation($"Outgoing response: {context.Response.StatusCode}");
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3: Configuring Middleware in the Pipeline&lt;/strong&gt;&lt;br&gt;
To register custom middleware in the HTTP pipeline, use the extension methods in the Program.cs or Startup.cs file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseLoggingMiddleware();
app.UseExceptionMiddleware();
app.UseAuthorizationMiddleware();

app.MapControllers();
app.Run();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Benefits of Middleware Extensions
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Readability&lt;/strong&gt;: Extension methods make pipeline configuration intuitive.&lt;br&gt;
&lt;strong&gt;Reusability&lt;/strong&gt;: Middleware can be reused across multiple applications.&lt;br&gt;
&lt;strong&gt;Separation of Concerns:&lt;/strong&gt; Each middleware handles a specific responsibility.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Custom middleware with extension methods streamlines your application's HTTP request pipeline. This approach not only enhances code readability but also aligns with the best practices of modular application design. By incorporating middlewares like logging, exception handling, and authorization, you can build robust and maintainable ASP.NET Core applications.&lt;/p&gt;

&lt;p&gt;Feel free to extend this concept further with caching, rate-limiting, or custom headers as middleware!&lt;/p&gt;

&lt;p&gt;Let me know in the comments how you use middleware in your projects or what custom middleware ideas you have! 🚀&lt;/p&gt;

</description>
      <category>security</category>
      <category>dotnet</category>
      <category>csharp</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Dependency Injection in ASP.NET Core with Extension Classes: A Comprehensive Guide</title>
      <dc:creator>Gaurav</dc:creator>
      <pubDate>Thu, 09 Jan 2025 03:04:29 +0000</pubDate>
      <link>https://forem.com/gaurav-nandankar/dependency-injection-in-aspnet-core-with-extension-classes-a-comprehensive-guide-25pn</link>
      <guid>https://forem.com/gaurav-nandankar/dependency-injection-in-aspnet-core-with-extension-classes-a-comprehensive-guide-25pn</guid>
      <description>&lt;p&gt;Dependency Injection (DI) is a fundamental design pattern in ASP.NET Core that promotes code reusability, maintainability, and testability. One of the best practices for organizing DI in large applications is to encapsulate service registrations using extension classes. This blog post will guide you through the use of DI with extension classes, using the provided example code for a hands-on understanding.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Dependency Injection?
&lt;/h2&gt;

&lt;p&gt;Dependency Injection is a design pattern used to achieve Inversion of Control (IoC) between classes and their dependencies. Instead of instantiating objects directly within a class, dependencies are injected, typically during runtime. This makes the application more modular and easier to test.&lt;/p&gt;

&lt;h2&gt;
  
  
  Benefits of Using Extension Classes for DI
&lt;/h2&gt;

&lt;p&gt;Separation of Concerns: Keeps the Program.cs or Startup.cs clean and manageable.&lt;br&gt;
Reusability: Allows encapsulation of DI logic for reuse across projects.&lt;br&gt;
Maintainability: Changes to service registrations can be made in one place without cluttering the main application configuration.&lt;/p&gt;
&lt;h2&gt;
  
  
  Example: Dependency Injection Using an Extension Class
&lt;/h2&gt;

&lt;p&gt;Here’s a complete example of using an extension class for DI in ASP.NET Core.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Add the Required NuGet Package&lt;/strong&gt;&lt;br&gt;
Make sure you have the required package installed:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;dotnet add package Microsoft.Extensions.DependencyInjection.Abstractions&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;2. Creating the Extension Class&lt;/strong&gt;&lt;br&gt;
The extension class encapsulates service registrations for better organization. Below is a class named AddDependencyInjection in the DependencyInjection namespace:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using Microsoft.Extensions.DependencyInjection;
using dumdum.Interface;
using dumdum.Model.DB;
using dumdum.Service.Implementation;
using dumdum.Service.Interface;
using Sieve.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using System.Text;
using Microsoft.IdentityModel.Tokens;

namespace dumdum.DependencyInjection
{
    public static class AddDependencyInjection
    {
        public static IServiceCollection AddDependencies(this IServiceCollection services)
        {
            // Database Context
            services.AddDbContext&amp;lt;Context&amp;gt;(options =&amp;gt;
                options.UseSqlServer(Environment.GetEnvironmentVariable("CodeXMinioService")));

            // General Services
            services.AddSingleton&amp;lt;IHttpContextAccessor, HttpContextAccessor&amp;gt;();
            services.AddScoped(typeof(IGenericRepository&amp;lt;&amp;gt;), typeof(GenericRepository&amp;lt;&amp;gt;));
            services.AddScoped&amp;lt;IUnitOfWork, UnitOfWork&amp;gt;();
            services.AddScoped(typeof(IBaseService&amp;lt;,&amp;gt;), typeof(BaseService&amp;lt;,&amp;gt;));
            services.AddScoped&amp;lt;ISieveProcessor, SieveProcessor&amp;gt;();
            services.AddScoped&amp;lt;ISQLORMService, DapperORMService&amp;gt;();

            // Business Logic Services
            services.AddScoped&amp;lt;IUploadService, UploadService&amp;gt;();
            services.AddScoped&amp;lt;IUserMaster, UserMasterService&amp;gt;();

            // JWT Authentication
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =&amp;gt;
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("your_secret_key_here")),
                        ValidateIssuer = false,
                        ValidateAudience = false,
                        ValidateLifetime = true,
                        ClockSkew = TimeSpan.Zero
                    };
                });

            return services;
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Using the Extension Method in Program.cs&lt;/strong&gt;&lt;br&gt;
With the extension class in place, the DI registrations can be easily included in the main entry point of your application:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using dumdum.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();

builder.Services.AddDependencies(); // Adding dependencies via extension method

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the middleware pipeline
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
app.Run();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Key Points in the Example
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Encapsulation of Services&lt;/strong&gt;: All the service registrations are encapsulated in the AddDependencies method, promoting reusability and maintainability.&lt;br&gt;
&lt;strong&gt;Modular Approach&lt;/strong&gt;: Each type of service (e.g., DbContext, repositories, business logic services) is grouped logically.&lt;br&gt;
&lt;strong&gt;JWT Authentication&lt;/strong&gt;: Secure your API by configuring AddJwtBearer with token validation parameters.&lt;/p&gt;

&lt;h2&gt;
  
  
  Benefits of the Approach
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Scalability&lt;/strong&gt;: Easily add more services to the extension method as your application grows.&lt;br&gt;
&lt;strong&gt;Code Organization&lt;/strong&gt;: Keeps DI logic separate from application startup code.&lt;br&gt;
&lt;strong&gt;Testability&lt;/strong&gt;: Simplifies unit testing by providing a centralized place to mock services.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Using extension methods for dependency injection is a best practice in ASP.NET Core that enhances code modularity and readability. By encapsulating service registrations in an extension class, you can keep your main application file clean while making the DI setup reusable and easy to maintain.&lt;/p&gt;

&lt;p&gt;Adopting this pattern in your projects will lead to more structured and professional code. Happy coding! 🚀&lt;/p&gt;

&lt;p&gt;Connect with me:&lt;a href="https://www.linkedin.com/in/iamgaurav110/" rel="noopener noreferrer"&gt;@LinkedIn&lt;/a&gt;&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>cleancode</category>
      <category>performance</category>
      <category>dotnet</category>
    </item>
    <item>
      <title>Securing Your .NET APIs with JWT Authentication</title>
      <dc:creator>Gaurav</dc:creator>
      <pubDate>Fri, 03 Jan 2025 02:13:21 +0000</pubDate>
      <link>https://forem.com/gaurav-nandankar/securing-your-net-apis-with-jwt-authentication-5978</link>
      <guid>https://forem.com/gaurav-nandankar/securing-your-net-apis-with-jwt-authentication-5978</guid>
      <description>&lt;p&gt;JSON Web Tokens (JWT) are a widely-used standard for securing APIs. In this post, we will explore how to implement JWT authentication in a .NET application, including generating tokens, configuring authentication middleware, and enabling Swagger to accept tokens for testing.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Prerequisites
&lt;/h2&gt;

&lt;p&gt;Before we begin, ensure your .NET project includes the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;ASP.NET Core&lt;/li&gt;
&lt;li&gt;NuGet Packages:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package Swashbuckle.AspNetCore
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. Generate JWT Tokens
&lt;/h2&gt;

&lt;p&gt;Add a Login endpoint to generate JWT tokens for authenticated users. Below is the implementation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public async Task&amp;lt;ActionResult&amp;gt; Login(string email, string password)
{
    var _user = _db.UserMaster.FirstOrDefault(x =&amp;gt; x.Email == email &amp;amp;&amp;amp; x.Password == password &amp;amp;&amp;amp; x.IsDeleted == false);
    if (_user == null)
    {
        return new BadRequestObjectResult("UnAuthorized");
    }

    // JWT Token generation
    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes("sdf5s4f6sd54fsdfsdf"); // Use a secure key and store it safely.
    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(new Claim[]
        {
            new Claim(ClaimTypes.Name, _user.Id.ToString()),
            new Claim(ClaimTypes.Email, _user.Email)
        }),
        Expires = DateTime.UtcNow.AddHours(1),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
    };

    var token = tokenHandler.CreateToken(tokenDescriptor);
    var tokenString = tokenHandler.WriteToken(token);

    return new OkObjectResult(new
    {
        Token = tokenString,
        ExpiresIn = tokenDescriptor.Expires
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Key Points:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Validate the user credentials (e.g., email and password).&lt;/li&gt;
&lt;li&gt;Generate a secure JWT token with claims.&lt;/li&gt;
&lt;li&gt;Return the token to the client.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  3. Configure JWT Authentication Middleware
&lt;/h2&gt;

&lt;p&gt;Add JWT authentication middleware in your Program.cs or Startup.cs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;builder.Services.AddAuthentication(Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =&amp;gt;
    {
        options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("sdf5s4f6sd54fsdfsdf")),
            ValidateIssuer = false,
            ValidateAudience = false,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero
        };

        options.Events = new JwtBearerEvents
        {
            OnAuthenticationFailed = context =&amp;gt;
            {
                context.Response.StatusCode = 401;
                context.Response.ContentType = "application/json";
                return context.Response.WriteAsync(JsonConvert.SerializeObject(new { Message = "Authentication Failed" }));
            },
            OnChallenge = context =&amp;gt;
            {
                context.HandleResponse();
                context.Response.StatusCode = 401;
                context.Response.ContentType = "application/json";
                return context.Response.WriteAsync(JsonConvert.SerializeObject(new { Message = "Token is missing or invalid" }));
            }
        };
    });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Key Points:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Validate the token's signature, expiration, and audience.&lt;/li&gt;
&lt;li&gt;Handle authentication errors gracefully.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  4. Secure API Endpoints
&lt;/h2&gt;

&lt;p&gt;Use the [Authorize] attribute to secure your endpoints:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[Authorize]
[HttpGet("secure-endpoint")]
public IActionResult SecureEndpoint()
{
    return Ok("This is a secure endpoint!");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Key Points:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Ensure all sensitive endpoints are protected with [Authorize].&lt;/li&gt;
&lt;li&gt;Add role-based authorization if needed.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  5. Enable Swagger to Accept JWT Tokens
&lt;/h2&gt;

&lt;p&gt;Add Swagger support for JWT authentication:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;builder.Services.AddSwaggerGen(c =&amp;gt;
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Your API", Version = "v1" });

    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer",
        BearerFormat = "JWT",
        In = ParameterLocation.Header,
        Description = "Enter 'Bearer' [space] and then your token in the text input below.\nExample: \"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9\""
    });

    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            Array.Empty&amp;lt;string&amp;gt;()
        }
    });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Key Points:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Add a Bearer Token input field in Swagger.&lt;/li&gt;
&lt;li&gt;Click the Authorize button in Swagger to authenticate.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  6. Test the Implementation
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Generate a token using the Login endpoint.&lt;/li&gt;
&lt;li&gt;Use Swagger or Postman to send requests to secured endpoints with the token in the Authorization header.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Example Header:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Authorization: Bearer &amp;lt;your_token_here&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  7. Conclusion
&lt;/h2&gt;

&lt;p&gt;By following these steps, you have successfully implemented JWT authentication in your .NET application. Your APIs are now secured, and Swagger provides an easy way to test the protected endpoints.&lt;/p&gt;

&lt;p&gt;Connect with me:&lt;a href="https://www.linkedin.com/in/iamgaurav110/" rel="noopener noreferrer"&gt;@LinkedIn&lt;/a&gt;&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>jwt</category>
      <category>security</category>
      <category>dotnet</category>
    </item>
    <item>
      <title>.NET Core MVC Project Structure : Implementing a Generic Service and Repository Pattern</title>
      <dc:creator>Gaurav</dc:creator>
      <pubDate>Tue, 03 Dec 2024 15:15:37 +0000</pubDate>
      <link>https://forem.com/gaurav-nandankar/implementing-a-generic-service-and-repository-pattern-in-net-core-njh</link>
      <guid>https://forem.com/gaurav-nandankar/implementing-a-generic-service-and-repository-pattern-in-net-core-njh</guid>
      <description>&lt;p&gt;In this post, we'll dive into how the Unit of Work and Repository Pattern simplify database access in .NET Core MVC applications. These patterns promote clean architecture, reusability, and a clear separation of concerns. Let's explore their implementation through an example using BaseService, GenericRepository, and UnitOfWork with a UserMasterService.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why Use the Repository and Unit of Work Pattern?&lt;/strong&gt;&lt;br&gt;
Repository Pattern: Encapsulates data access logic, keeping it clean and isolated. It serves as a mediator between the data access layer and the business logic layer.&lt;br&gt;
Unit of Work Pattern: Ensures consistency across multiple repositories during transactions. By grouping operations under a single transaction, it simplifies error handling and rollback processes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Repository Pattern:&lt;/strong&gt; Encapsulates data access logic, making the codebase cleaner and easier to maintain.&lt;br&gt;
&lt;strong&gt;Unit of Work Pattern:&lt;/strong&gt; Ensures consistency across transactions by coordinating changes to multiple repositories.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhxwoolt1adhavco2qy7n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhxwoolt1adhavco2qy7n.png" alt="Image description" width="283" height="665"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  1. BaseService
&lt;/h2&gt;

&lt;p&gt;Purpose: A generic service layer that provides CRUD operations for any entity type inheriting from AuditableEntity. This promotes code reuse and consistency across the application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Methods:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create: Adds a new entity to the database. If the entity is AuditableEntity, it automatically sets audit properties like creation date.&lt;br&gt;
Retrieve: Fetches all records for an entity type from the database with AsNoTracking for better performance on read-only queries.&lt;br&gt;
RetrieveByID: Retrieves a single entity by its ID using the repository.&lt;br&gt;
Update: Finds an existing entity by ID, updates its properties, and saves changes.&lt;br&gt;
Delete: Performs a soft delete by setting the IsDeleted flag, ensuring data is not permanently removed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using manage_my_assets.App;
using manage_my_assets.Models;
using manage_my_assets.Service.Interface;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;

namespace manage_my_assets.Service.Implementation
{
    public class BaseService&amp;lt;T&amp;gt; : IBaseService&amp;lt;T&amp;gt; where T : AuditableEntity
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly AppDbContext _dbContext;

        public BaseService(AppDbContext dbContext, IUnitOfWork unitOfWork)
        {
            _dbContext = dbContext;
            _unitOfWork = unitOfWork;
        }

        public async Task&amp;lt;T&amp;gt; Create(T entity)
        {
            if (entity is AuditableEntity auditableEntity)
            {
                auditableEntity.SetAuditableProperties();
            }

            await _unitOfWork.Repository&amp;lt;T&amp;gt;().Insert(entity);
            await _unitOfWork.SaveChangesAsync();
            return entity;
        }

        public async Task&amp;lt;bool&amp;gt; Delete(int id)
        {
            var entity = await _unitOfWork.Repository&amp;lt;T&amp;gt;().GetById(id);
            if (entity == null) return false;

            _unitOfWork.Repository&amp;lt;T&amp;gt;().Delete(entity);
            await _unitOfWork.SaveChangesAsync();
            return true;
        }

        public async Task&amp;lt;List&amp;lt;T&amp;gt;&amp;gt; Retrieve()
        {
            return await _dbContext.Set&amp;lt;T&amp;gt;().AsNoTracking().ToListAsync();
        }

        public async Task&amp;lt;T&amp;gt; RetrieveByID(int id)
        {
            return await _unitOfWork.Repository&amp;lt;T&amp;gt;().GetById(id);
        }

        public async Task&amp;lt;T&amp;gt; Update(int id, T entity)
        {
            var existingEntity = await _unitOfWork.Repository&amp;lt;T&amp;gt;().GetById(id);
            if (existingEntity == null) return null;

            if (existingEntity is AuditableEntity auditableEntity)
            {
                auditableEntity.UpdateAuditableProperties();
            }

            // Assuming a method to update entity properties from the provided entity
            _unitOfWork.Repository&amp;lt;T&amp;gt;().Update(existingEntity);
            await _unitOfWork.SaveChangesAsync();

            return existingEntity;
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. GenericRepository
&lt;/h2&gt;

&lt;p&gt;Purpose: A reusable repository that handles data access operations such as Insert, Update, Delete, and GetAll for any entity.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CRUD Operations:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;GetAll: Fetches all non-deleted records.&lt;br&gt;
Insert: Adds a new entity to the database.&lt;br&gt;
Update: Updates an entity’s state in the database.&lt;br&gt;
GetById: Retrieves an entity by ID, ensuring it hasn’t been soft deleted.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using manage_my_assets.App;
using manage_my_assets.Models;
using manage_my_assets.Service.Interface;
using Microsoft.EntityFrameworkCore;

namespace manage_my_assets.Service.Implementation
{
    public class GenericRepository&amp;lt;T&amp;gt; : IGenericRepository&amp;lt;T&amp;gt; where T : AuditableEntity
    {
        protected readonly AppDbContext _dbContext;

        public GenericRepository(AppDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public T Delete(T entity)
        {
            //_dbContext.Set&amp;lt;T&amp;gt;().Remove(entity); //hard delete
            entity.IsDeleted = true; //soft delete
            _dbContext.Set&amp;lt;T&amp;gt;().Update(entity);
            return entity;
        }

        public async Task&amp;lt;IEnumerable&amp;lt;T&amp;gt;&amp;gt; GetAll()
        {
            return await _dbContext.Set&amp;lt;T&amp;gt;().Where(x =&amp;gt; x.IsDeleted == false).ToListAsync();
        }

        public async Task&amp;lt;T&amp;gt; GetById(int id)
        {
            var response = await _dbContext.Set&amp;lt;T&amp;gt;().FindAsync(id);
            if (response.IsDeleted) //check for soft delete
                return null;
            return response;
        }

        public async Task&amp;lt;T&amp;gt; Insert(T entity)
        {
            var res = typeof(T);

            await _dbContext.Set&amp;lt;T&amp;gt;().AddAsync(entity);
            return entity;
        }

        public T Update(T entity)
        {
            _dbContext.Set&amp;lt;T&amp;gt;().Update(entity);
            return entity;
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. UnitOfWork
&lt;/h2&gt;

&lt;p&gt;Purpose: Orchestrates transactions across multiple repositories, ensuring a consistent and reliable database state.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using manage_my_assets.App;
using manage_my_assets.Models;
using manage_my_assets.Service.Interface;

namespace manage_my_assets.Service.Implementation
{
    public class UnitOfWork : IUnitOfWork
    {
        protected readonly AppDbContext _dbContext;
        private readonly IDictionary&amp;lt;Type, dynamic&amp;gt; _repositories;

        public UnitOfWork(AppDbContext dbContext)
        {
            _repositories = new Dictionary&amp;lt;Type, dynamic&amp;gt;();
            _dbContext = dbContext;
        }

        public IGenericRepository&amp;lt;T&amp;gt; Repository&amp;lt;T&amp;gt;() where T : AuditableEntity
        {
            var entityType = typeof(T);

            if (_repositories.ContainsKey(entityType))
            {
                return _repositories[entityType];
            }

            var repositoryType = typeof(GenericRepository&amp;lt;&amp;gt;);

            var repository = Activator.CreateInstance(repositoryType.MakeGenericType(typeof(T)), _dbContext);

            if (repository == null)
            {
                throw new NullReferenceException("Repository should not be null");
            }

            _repositories.Add(entityType, repository);

            return (IGenericRepository&amp;lt;T&amp;gt;)repository;
        }

        public async Task&amp;lt;int&amp;gt; SaveChangesAsync()
        {
            return await _dbContext.SaveChangesAsync();
        }

        public async Task RollBackChangesAsync()
        {
            await _dbContext.Database.RollbackTransactionAsync();
        }


    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Dependency Injection in Program.cs&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using manage_my_assets.App;
using manage_my_assets.Service.Implementation;
using manage_my_assets.Service.Interface;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddDbContext&amp;lt;AppDbContext&amp;gt;(x=&amp;gt;x.UseSqlServer(builder.Configuration.GetConnectionString("ManagerConnectionString")));

builder.Services.AddScoped(typeof(IGenericRepository&amp;lt;&amp;gt;), typeof(GenericRepository&amp;lt;&amp;gt;));
builder.Services.AddScoped&amp;lt;IUnitOfWork, UnitOfWork&amp;gt;();
builder.Services.AddScoped(typeof(IBaseService&amp;lt;&amp;gt;), typeof(BaseService&amp;lt;&amp;gt;));

builder.Services.AddScoped&amp;lt;IUserMasterService, UserMasterService&amp;gt;();

var app = builder.Build();

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

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

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

app.Run();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Integration in Application&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ProductController : Controller
{
    private readonly IUnitOfWork _unitOfWork;

    public ProductController(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    public async Task&amp;lt;IActionResult&amp;gt; Index()
    {
        var products = await _unitOfWork.Repository&amp;lt;Product&amp;gt;().GetAll();
        return View(products);
    }

    [HttpPost]
    public async Task&amp;lt;IActionResult&amp;gt; AddProduct(Product product)
    {
        await _unitOfWork.Repository&amp;lt;Product&amp;gt;().Insert(product);
        await _unitOfWork.SaveChangesAsync();
        return RedirectToAction("Index");
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Summary of Flow&lt;/strong&gt;&lt;br&gt;
Services like UnitOfWork, BaseService, and repositories are registered in the DI container.&lt;br&gt;
Controllers or services request these dependencies through constructor injection.&lt;br&gt;
The UnitOfWork is used to coordinate repository operations and manage transactions.&lt;br&gt;
The application pipeline ensures a structured flow for requests, middleware, and responses.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Implementing the Unit of Work and Repository Pattern in an ASP.NET Core MVC application provides a modular, maintainable, and testable architecture. Here's why this approach is effective:&lt;br&gt;
Centralized Data Access: The UnitOfWork ensures a single entry point for managing multiple repositories, making it easier to coordinate operations across multiple data entities.&lt;br&gt;
Separation of Concerns: By abstracting data access logic into repositories and services, this design keeps your controllers focused on application flow and user interactions.&lt;br&gt;
Consistency and Reusability:&lt;br&gt;
The generic repository pattern eliminates redundant code by providing reusable CRUD operations.&lt;br&gt;
Soft delete mechanisms (as seen in GenericRepository) ensure data consistency while preserving historical records.&lt;br&gt;
Transaction Management: The UnitOfWork ensures that database changes across repositories are saved or rolled back as a single unit, enhancing data integrity.&lt;br&gt;
Scalability: As the application grows, new entities and business logic can be easily added without disrupting the existing structure.&lt;br&gt;
Ease of Testing: Dependency injection of repositories and UnitOfWork allows for mocking during unit tests, ensuring testable and reliable code.&lt;br&gt;
By adopting this structure, your application gains a robust foundation that streamlines development, reduces redundancy, and improves code readability. This design pattern is ideal for scalable applications with complex business logic and multiple data entities.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Connect with me:&lt;a href="https://www.linkedin.com/in/iamgaurav110/" rel="noopener noreferrer"&gt;@ LinkedIn&lt;/a&gt;&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>dotnet</category>
      <category>dotnetcore</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Angular 17+ Fundamentals : Everything you need to know in one place</title>
      <dc:creator>Gaurav</dc:creator>
      <pubDate>Sun, 06 Oct 2024 12:09:54 +0000</pubDate>
      <link>https://forem.com/gaurav-nandankar/angular-17-fundamentals-1ha8</link>
      <guid>https://forem.com/gaurav-nandankar/angular-17-fundamentals-1ha8</guid>
      <description>&lt;p&gt;If you're here, you're probably already interested in learning Angular and want to dive right into the fundamentals. There's no need to convince you why Angular is a powerful framework—you're likely aware of its popularity for building scalable, single-page applications. This guide is all about getting hands-on with Angular, so we’ll skip the sales pitch and jump straight into the essentials.&lt;/p&gt;

&lt;p&gt;From setting up routing to handling complex data flows with signals, computed values, and deferrable views, this post will guide you through the key concepts you'll need to build dynamic, efficient Angular applications. Whether you're just getting started or need a quick refresher, I’ve got you covered with practical examples and explanations for every topic.&lt;/p&gt;

&lt;p&gt;Let’s dive in!&lt;/p&gt;

&lt;h2&gt;
  
  
  Table of Contents
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Routing&lt;/li&gt;
&lt;li&gt;Standalone Components&lt;/li&gt;
&lt;li&gt;Forms&lt;/li&gt;
&lt;li&gt;Property Binding&lt;/li&gt;
&lt;li&gt;Event Handling&lt;/li&gt;
&lt;li&gt;Conditional Rendering&lt;/li&gt;
&lt;li&gt;For Loops in Angular&lt;/li&gt;
&lt;li&gt;Passing Data Between Components&lt;/li&gt;
&lt;li&gt;Reactive Primitives: Signals, Computed, and Effects&lt;/li&gt;
&lt;li&gt;Deferrable Views&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  1. Routing
&lt;/h2&gt;

&lt;p&gt;Routing allows you to navigate between different views in an Angular app. Here’s how routing is set up in Angular 17:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Routes } from '@angular/router';
import { BasicsComponent } from './basics/basics.component';
import { HomeComponent } from './home/home.component';
import { UserCardViewComponent } from './user-card-view/user-card-view.component';
import { OutputComponentComponent } from './output-component/output-component.component';

export const routes: Routes = [
    {
        path: 'basics',
        component: BasicsComponent
    },
    {
        path: '',
        component: HomeComponent
    },
    {
        // Passing data in the component from the URL
        path: 'user-card-view/:username',
        component: UserCardViewComponent
    },
    {
        path: 'output-view',
        component: OutputComponentComponent
    }
];

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Description:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt; Dynamic Routes: In the user-card-view/:username route, :username is a dynamic parameter passed from the URL to the component.&lt;/li&gt;
&lt;li&gt;Empty Path (path: ''): Navigating to the root of the application will load HomeComponent.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  2. Standalone Components
&lt;/h2&gt;

&lt;p&gt;Angular 17 introduced standalone components, making them more modular and independent. You can import other modules or components directly into a standalone component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Component } from '@angular/core';
import { UserCardViewComponent } from '../user-card-view/user-card-view.component';
import { Router, RouterLink } from '@angular/router';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@Component({
  selector: 'app-basics',
  standalone: true,
  imports: [UserCardViewComponent, RouterLink, FormsModule, ReactiveFormsModule],
  templateUrl: './basics.component.html',
  styleUrls: ['./basics.component.css']
})
export class BasicsComponent {
  // Component logic goes here
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Description:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Standalone components reduce the dependency on Angular modules and allow for more modular development. You can directly import other components, directives, and services into them.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  3. Forms
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Template-Driven Forms&lt;/strong&gt;&lt;br&gt;
Template-driven forms are quick to set up but are best for simpler use cases:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;form name="loginForm"&amp;gt;
    &amp;lt;label for="username"&amp;gt;Username:&amp;lt;/label&amp;gt;
    &amp;lt;input type="text" name="username" [(ngModel)]="username"&amp;gt;

    &amp;lt;label for="password"&amp;gt;Password:&amp;lt;/label&amp;gt;
    &amp;lt;input type="password" name="password" [(ngModel)]="password"&amp;gt;
&amp;lt;/form&amp;gt;

&amp;lt;p&amp;gt;Username: {{ username }}&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;Password: {{ password }}&amp;lt;/p&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Reactive Forms&lt;/strong&gt;&lt;br&gt;
Reactive forms are more powerful and scalable, especially for larger applications:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;loginForm = new FormGroup({
    username: new FormControl(''),
    password: new FormControl('')
});

handleSubmit() {
    console.log(this.loginForm.value);
}

&amp;lt;form [formGroup]="loginForm" (ngSubmit)="handleSubmit()"&amp;gt;
    &amp;lt;label for="username"&amp;gt;Username:&amp;lt;/label&amp;gt;
    &amp;lt;input formControlName="username"&amp;gt;

    &amp;lt;label for="password"&amp;gt;Password:&amp;lt;/label&amp;gt;
    &amp;lt;input formControlName="password"&amp;gt;

    &amp;lt;button type="submit"&amp;gt;Submit&amp;lt;/button&amp;gt;
&amp;lt;/form&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Description:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Template-driven forms are quick to implement but require more effort when adding validation.&lt;/li&gt;
&lt;li&gt;Reactive forms are highly configurable, providing better control over form state and validation.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  4. Property Binding
&lt;/h2&gt;

&lt;p&gt;Property binding dynamically sets properties in the DOM. This is done using square brackets [ ].&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button [disabled]="isDisabled"&amp;gt;Submit&amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;isDisabled = true;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Description:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Here, the button is disabled based on the value of isDisabled. Property binding updates the DOM property dynamically as the component's property changes.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  5. Event Handling
&lt;/h2&gt;

&lt;p&gt;Event binding allows you to respond to user interactions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button (click)="handleClick()"&amp;gt;Submit&amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;handleClick() {
  console.log('Button clicked!');
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Description:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The event handler handleClick() is invoked whenever the button is clicked.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  6. Conditional Rendering
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;If-Else Statements&lt;/strong&gt;&lt;br&gt;
You can control the visibility of elements using *ngIf.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@if(card.type === 'gold') {
    &amp;lt;span&amp;gt;Gold&amp;lt;/span&amp;gt;
} @else if(card.type === 'silver') {
    &amp;lt;span&amp;gt;Silver&amp;lt;/span&amp;gt;
} @else if(card.type === 'platinum') {
    &amp;lt;span&amp;gt;Platinum&amp;lt;/span&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Switch-Case&lt;/strong&gt;&lt;br&gt;
For complex conditions, you can use &lt;code&gt;@switch&lt;/code&gt; to improve readability.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@switch(card.type) {
    @case('gold') {
        &amp;lt;span&amp;gt;Gold&amp;lt;/span&amp;gt;
    }
    @case('silver') {
        &amp;lt;span&amp;gt;Silver&amp;lt;/span&amp;gt;
    }
    @case('platinum') {
        &amp;lt;span&amp;gt;Platinum&amp;lt;/span&amp;gt;
    }
    @default {
        &amp;lt;span&amp;gt;Unknown Type&amp;lt;/span&amp;gt;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Description:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If-Else is used for simple conditionals.&lt;/li&gt;
&lt;li&gt;Switch-Case is preferred when you need to handle multiple conditions, especially for readability and scalability.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  7. For Loops in Angular
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;@for&lt;/code&gt; directive lets you iterate over an array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@for(item of cardList; track item) {
    &amp;lt;div class="card"&amp;gt;
        &amp;lt;h5&amp;gt;{{item.name}}&amp;lt;/h5&amp;gt;
        &amp;lt;p&amp;gt;{{item.number}}&amp;lt;/p&amp;gt;
        &amp;lt;span&amp;gt;{{item.type}}&amp;lt;/span&amp;gt;
    &amp;lt;/div&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Description:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;trackBy improves performance by uniquely identifying each item, ensuring the DOM efficiently handles large lists.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  8. Passing Data Between Components
&lt;/h2&gt;

&lt;p&gt;You can pass data between parent and child components using &lt;code&gt;@Input()&lt;/code&gt; and &lt;code&gt;@Output()&lt;/code&gt;&lt;br&gt;
 &lt;strong&gt;Sending Data to Child Component&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;app-user-card-view [userCardData]="card"&amp;gt;&amp;lt;/app-user-card-view&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In UserCardViewComponent:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Input() userCardData: CardModel;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Sending Data Back to Parent&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Output() selectedCard = new EventEmitter&amp;lt;any&amp;gt;();
sendDataToAnotherComponent() {
  this.selectedCard.emit(this.cardList);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Description:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;@Input()&lt;/code&gt; allows a parent component to pass data to its child.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;@Output()&lt;/code&gt; uses EventEmitter to send data from the child back to the parent component.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  9. Reactive Primitives: Signals, Computed, and Effects
&lt;/h2&gt;

&lt;p&gt;Angular 17 introduced Signals and Computed values for reactive programming.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Signals&lt;/strong&gt;&lt;br&gt;
Signals are reactive variables that automatically notify Angular when they change.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;firstName = signal("Gaurav");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Computed Values&lt;/strong&gt;&lt;br&gt;
Computed values derive from other reactive values (signals).&lt;/p&gt;

&lt;p&gt;&lt;code&gt;fullName = computed(() =&amp;gt;&lt;/code&gt;${this.firstName()} ${this.lastName()}&lt;code&gt;);&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Effects&lt;/strong&gt;&lt;br&gt;
Effects allow you to react to changes in signals or perform side effects.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;effect(() =&amp;gt; console.log(&lt;/code&gt;Full Name: ${this.fullName()}&lt;code&gt;));&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Description:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Signals provide a reactive data model, reducing the need for manual change detection.&lt;/li&gt;
&lt;li&gt;Computed Values derive new values from existing signals.&lt;/li&gt;
&lt;li&gt;Effects are used to perform actions when signals change.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  10. Deferrable Views
&lt;/h2&gt;

&lt;p&gt;Deferrable views allow for lazy-loading parts of the UI, based on certain conditions or user interactions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Basic Example&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button #trigger&amp;gt;Load More&amp;lt;/button&amp;gt;

@defer (on interaction(trigger)) {
    &amp;lt;p&amp;gt;Content loaded.&amp;lt;/p&amp;gt;
} @loading {
    &amp;lt;p&amp;gt;Loading...&amp;lt;/p&amp;gt;
} @error {
    &amp;lt;p&amp;gt;Error loading content.&amp;lt;/p&amp;gt;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Advanced Example: Conditional Lazy Loading&lt;/strong&gt;&lt;br&gt;
You can defer loading content based on specific conditions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button (click)="counter = counter - 1"&amp;gt;Make it Zero: {{counter}}&amp;lt;/button&amp;gt;

@defer (when counter == 0) {
    &amp;lt;p&amp;gt;Content loaded when counter hits 0!&amp;lt;/p&amp;gt;
} @placeholder {
    &amp;lt;p&amp;gt;Waiting for counter to hit 0...&amp;lt;/p&amp;gt;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Description:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Deferrable Views improve performance by delaying the loading of heavy components until necessary.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;@loading&lt;/code&gt;, &lt;code&gt;@error&lt;/code&gt;, and &lt;code&gt;@placeholder&lt;/code&gt; directives provide a better user experience by giving feedback during the loading process.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
This guide walks you through key Angular concepts like routing, standalone components, forms, and reactive primitives. With Angular 17’s new features like signals and deferrable views, you can create more efficient and reactive web applications.&lt;/p&gt;

&lt;p&gt;Connect with me:&lt;a href="https://www.linkedin.com/in/iamgaurav110/" rel="noopener noreferrer"&gt;@ LinkedIn&lt;/a&gt;&lt;/p&gt;

</description>
      <category>angular</category>
      <category>typescript</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
    <item>
      <title>How to Make API Calls in Android Using Kotlin</title>
      <dc:creator>Gaurav</dc:creator>
      <pubDate>Sat, 28 Sep 2024 01:51:49 +0000</pubDate>
      <link>https://forem.com/gaurav-nandankar/how-to-make-api-calls-in-android-using-kotlin-mpd</link>
      <guid>https://forem.com/gaurav-nandankar/how-to-make-api-calls-in-android-using-kotlin-mpd</guid>
      <description>&lt;p&gt;In modern mobile app development, integrating with RESTful APIs is a common task. Often, these APIs require different types of HTTP methods, such as GET, POST, PUT, and DELETE, for different operations. In this blog post, we will walk through how to create a generic utility in Kotlin that allows you to call any of these methods seamlessly.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why You Need a Generic API Call Utility
&lt;/h2&gt;

&lt;p&gt;Rather than creating different functions for each HTTP method, it's more efficient to have a single method that can handle all types of requests. This helps in writing clean and maintainable code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step-by-Step Guide to Create a Generic API Utility
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Setting Up the API Utility Class&lt;/strong&gt;&lt;br&gt;
Let’s start by creating an API utility class that handles all types of HTTP methods (&lt;strong&gt;GET&lt;/strong&gt;, &lt;strong&gt;POST&lt;/strong&gt;, &lt;strong&gt;PUT&lt;/strong&gt;, &lt;strong&gt;DELETE&lt;/strong&gt;). We'll use HttpURLConnection for this purpose, as it's a part of the Java standard library and works well for simple HTTP requests.&lt;/p&gt;

&lt;p&gt;Here's the code for the utility:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class API {

    companion object {
        // Function to handle all HTTP methods
        fun callApi(apiUrl: String, token: String, httpMethod: String, requestModel: Any? = null): String {
            val response = StringBuilder()

            try {
                val url = URL(apiUrl)
                val connection = url.openConnection() as HttpURLConnection
                connection.requestMethod = httpMethod // Set the HTTP method (GET, POST, PUT, DELETE)

                // Set request headers for JSON format and authorization
                connection.setRequestProperty("Content-Type", "application/json")
                connection.setRequestProperty("Accept", "application/json")
                connection.setRequestProperty("Authorization", "Bearer $token")

                // Send request body for POST/PUT methods
                if (httpMethod == "POST" || httpMethod == "PUT") {
                    connection.doOutput = true
                    requestModel?.let {
                        val jsonInput = Gson().toJson(it)
                        OutputStreamWriter(connection.outputStream).use { os -&amp;gt;
                            os.write(jsonInput)
                            os.flush()
                        }
                    }
                }

                // Handle the response
                val responseCode = connection.responseCode
                if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
                    BufferedReader(InputStreamReader(connection.inputStream, "utf-8")).use { br -&amp;gt;
                        var responseLine: String?
                        while (br.readLine().also { responseLine = it } != null) {
                            response.append(responseLine?.trim())
                        }
                    }
                } else {
                    // Handle error response
                    BufferedReader(InputStreamReader(connection.errorStream, "utf-8")).use { br -&amp;gt;
                        var responseLine: String?
                        while (br.readLine().also { responseLine = it } != null) {
                            response.append(responseLine?.trim())
                        }
                    }
                    println("Error Response Code: $responseCode, Message: ${connection.responseMessage}")
                }
            } catch (e: Exception) {
                e.printStackTrace()
                return e.message.toString()
            }

            return response.toString()
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. How It Works
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;HTTP Method&lt;/strong&gt;: The function accepts an HTTP method (POST, GET, PUT, DELETE) and sets it dynamically using the requestMethod property.&lt;br&gt;
&lt;strong&gt;Authorization:&lt;/strong&gt; The Authorization header is set using a Bearer token.&lt;br&gt;
&lt;strong&gt;Request Body:&lt;/strong&gt; For POST and PUT methods, the request body is serialized to JSON using Gson and sent along with the request.&lt;br&gt;
&lt;strong&gt;Response Handling:&lt;/strong&gt; If the response code is 200 OK or 201 Created, the response body is read and returned. Otherwise, the error message is captured.&lt;/p&gt;
&lt;h2&gt;
  
  
  3. How to Call the Utility
&lt;/h2&gt;

&lt;p&gt;You can use this utility in your Android application for any type of API call.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1: POST Request&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val apiUrl = "https://api.example.com/v1/resource"
val token = "your_token_here"

val requestBody = mapOf(
    "field1" to "value1",
    "field2" to "value2"
)

val response = API.callApi(apiUrl, token, "POST", requestBody)
println(response)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Example 2: GET Request&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val apiUrl = "https://api.example.com/v1/resource/1"
val token = "your_token_here"

// No request body for GET
val response = API.callApi(apiUrl, token, "GET")
println(response)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Example 3: PUT Request&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val apiUrl = "https://api.example.com/v1/resource/1"
val token = "your_token_here"

val requestBody = mapOf(
    "field1" to "new_value1",
    "field2" to "new_value2"
)

val response = API.callApi(apiUrl, token, "PUT", requestBody)
println(response)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Example 4: DELETE Request&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;val apiUrl = "https://api.example.com/v1/resource/{id}"
val token = "your_token_here"

// No request body for DELETE
val response = API.callApi(apiUrl, token, "DELETE")
println(response)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4. Adding Network Permissions&lt;/strong&gt;&lt;br&gt;
Don't forget to add the necessary permissions for network access in your &lt;strong&gt;AndroidManifest.xml&lt;/strong&gt; file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;uses-permission android:name="android.permission.INTERNET" /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;By creating a generic API utility, you can easily handle multiple types of HTTP requests (&lt;strong&gt;GET&lt;/strong&gt;, &lt;strong&gt;POST&lt;/strong&gt;, &lt;strong&gt;PUT&lt;/strong&gt;, &lt;strong&gt;DELETE&lt;/strong&gt;) in your Android applications. This approach keeps your code clean, reusable, and easy to maintain, ensuring efficient communication with external APIs.&lt;/p&gt;

&lt;p&gt;With this setup, you can quickly integrate with RESTful APIs in any Android project, saving time and reducing complexity.&lt;/p&gt;

&lt;p&gt;That's all for today.&lt;/p&gt;

&lt;p&gt;And also, share your favourite web dev resources to help the beginners here!&lt;/p&gt;

&lt;p&gt;Connect with me:&lt;a href="https://www.linkedin.com/in/iamgaurav110/" rel="noopener noreferrer"&gt;@ LinkedIn&lt;/a&gt; &lt;/p&gt;

</description>
      <category>mobile</category>
      <category>kotlin</category>
      <category>api</category>
      <category>postman</category>
    </item>
    <item>
      <title>Family Tree View in .NET MVC</title>
      <dc:creator>Gaurav</dc:creator>
      <pubDate>Mon, 26 Aug 2024 15:34:01 +0000</pubDate>
      <link>https://forem.com/gaurav-nandankar/tree-view-in-net-mvc-2e1i</link>
      <guid>https://forem.com/gaurav-nandankar/tree-view-in-net-mvc-2e1i</guid>
      <description>&lt;p&gt;A couple of days ago, a candidate came in for an interview at the company where I work. He was given a task to create a dynamic family tree chart in .NET MVC, where each parent node would have two child nodes. The challenge was that when logging in with a child node, that node should move to the top of the tree as the new parent.&lt;/p&gt;

&lt;p&gt;Watching him attempt the task reminded me of my own interview here, where I was given the same assignment. I remember how challenging it was to not only understand the logic but also to implement it visually in a tree-like structure. Unfortunately, the candidate struggled with creating the view, even though he had a good grasp of the underlying logic.&lt;/p&gt;

&lt;p&gt;I realized that this is a common challenge, so I decided to write a blog post to help others who might encounter this task in the future. Today, I’m going to guide you on how to create a family tree view in .NET MVC.&lt;/p&gt;

&lt;p&gt;Project Structure :&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgbel25id24buwb3kg127.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgbel25id24buwb3kg127.png" alt="Image description" width="308" height="646"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here, we're going to use Html.Partial to render our nodes and a for loop to iterate multiple times. By default, we should have a user called "admin" (in my case, but you can create a different user if you prefer).&lt;/p&gt;

&lt;p&gt;First, let's connect the .NET project with the database. For that, use the following model. We’re going to use username as the main node, with leftmember and rightmember as their children. This structure will continue recursively, with each node having two child nodes. If a node has not yet been created, a button will be available to add it.&lt;/p&gt;

&lt;p&gt;Model&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace TASK_1._1.Models
{
    public class UserModel
    {
        [Key]
        public int userId { get; set; }
        [Required]
        public string firstName { get; set; }
        [Required]
        public string lastName { get; set; }
        [Required]
        public string userName { get; set; }
        [Required]
        public string password { get; set; }
        public string leftMember { get; set; } = "";
        public string rightMember { get; set; } = "";
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Login View&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div class="align-content-center"&amp;gt;
    &amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;
    &amp;lt;form action="Auth" method="post"&amp;gt;

        &amp;lt;div class="container"&amp;gt;
            &amp;lt;label for="uname"&amp;gt;&amp;lt;b&amp;gt;Username&amp;lt;/b&amp;gt;&amp;lt;/label&amp;gt;
            &amp;lt;input type="text" placeholder="Enter Username" name="username" asp-route-username="username" required&amp;gt; &amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;

            &amp;lt;label for="psw"&amp;gt;&amp;lt;b&amp;gt;Password&amp;lt;/b&amp;gt;&amp;lt;/label&amp;gt;
            &amp;lt;input type="password" placeholder="Enter Password" name="password" asp-route-password="password" required&amp;gt;&amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;

            &amp;lt;button type="submit" asp-action="Auth"&amp;gt;Login&amp;lt;/button&amp;gt;
            &amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;
        &amp;lt;/div&amp;gt;


    &amp;lt;/form&amp;gt;

&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Index Page&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@inject TASK_1._1.Context.ApplicationDbContext context
@model List&amp;lt;UserModel&amp;gt; 
@{
    ViewData["Title"] = "Home Page"; 
}

&amp;lt;div class="text-center"&amp;gt;
    @if (Model != null &amp;amp;&amp;amp; Model.Count() &amp;gt; 0)
    {  
        &amp;lt;table border="1" class="text-center"&amp;gt;  
            @foreach (var user in Model)
            { 
                @Html.Partial("_UserNodeView", user)
                break;
            }
        &amp;lt;/table&amp;gt; 
    }
&amp;lt;/div&amp;gt;  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;RegisterLeftMember&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@model UserModel
@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}
&amp;lt;div class="text-center"&amp;gt;

    &amp;lt;form action="AddMemberLeft" method="post"&amp;gt;

        &amp;lt;div class="container"&amp;gt;

            &amp;lt;label for="uname"&amp;gt;&amp;lt;b&amp;gt;First Name&amp;lt;/b&amp;gt;&amp;lt;/label&amp;gt;
            &amp;lt;input type="text" placeholder="Enter First Name" asp-for="firstName" required&amp;gt; &amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;

            &amp;lt;label for="uname"&amp;gt;&amp;lt;b&amp;gt;Last Name&amp;lt;/b&amp;gt;&amp;lt;/label&amp;gt;
            &amp;lt;input type="text" placeholder="Enter Last Name" asp-for="lastName" required&amp;gt; &amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;

            &amp;lt;label for="uname"&amp;gt;&amp;lt;b&amp;gt;Username&amp;lt;/b&amp;gt;&amp;lt;/label&amp;gt;
            &amp;lt;input type="text" placeholder="Enter Username" asp-for="userName" required&amp;gt; &amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;

            &amp;lt;label for="psw"&amp;gt;&amp;lt;b&amp;gt;Password&amp;lt;/b&amp;gt;&amp;lt;/label&amp;gt;
            &amp;lt;input type="password" placeholder="Enter Password" asp-for="password" required&amp;gt;&amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;

            &amp;lt;button type="submit" asp-action="AddMemberLeft"&amp;gt;Create&amp;lt;/button&amp;gt;
            &amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;
        &amp;lt;/div&amp;gt;

    &amp;lt;/form&amp;gt;

&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;RegisterRightMember&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@model UserModel
@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}
&amp;lt;div class="text-center"&amp;gt;

    &amp;lt;form action="AddMemberRight" method="post"&amp;gt;

        &amp;lt;div class="container"&amp;gt;

            &amp;lt;label for="uname"&amp;gt;&amp;lt;b&amp;gt;First Name&amp;lt;/b&amp;gt;&amp;lt;/label&amp;gt;
            &amp;lt;input type="text" placeholder="Enter First Name" asp-for="firstName" required&amp;gt; &amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;

            &amp;lt;label for="uname"&amp;gt;&amp;lt;b&amp;gt;Last Name&amp;lt;/b&amp;gt;&amp;lt;/label&amp;gt;
            &amp;lt;input type="text" placeholder="Enter Last Name" asp-for="lastName" required&amp;gt; &amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;

            &amp;lt;label for="uname"&amp;gt;&amp;lt;b&amp;gt;Username&amp;lt;/b&amp;gt;&amp;lt;/label&amp;gt;
            &amp;lt;input type="text" placeholder="Enter Username" asp-for="userName" required&amp;gt; &amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;

            &amp;lt;label for="psw"&amp;gt;&amp;lt;b&amp;gt;Password&amp;lt;/b&amp;gt;&amp;lt;/label&amp;gt;
            &amp;lt;input type="password" placeholder="Enter Password" asp-for="password" required&amp;gt;&amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;

            &amp;lt;button type="submit" asp-action="AddMemberRight"&amp;gt;Create&amp;lt;/button&amp;gt;
            &amp;lt;br /&amp;gt;&amp;lt;br /&amp;gt;
        &amp;lt;/div&amp;gt;

    &amp;lt;/form&amp;gt;

&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;_Layout.cshtml&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;meta charset="utf-8" /&amp;gt;
    &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&amp;gt;
    &amp;lt;title&amp;gt;@ViewData["Title"] - TASK_1._1&amp;lt;/title&amp;gt;
    &amp;lt;link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" /&amp;gt;
    &amp;lt;link rel="stylesheet" href="~/css/site.css" asp-append-version="true" /&amp;gt;
    &amp;lt;link rel="stylesheet" href="~/TASK_1._1.styles.css" asp-append-version="true" /&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    &amp;lt;header&amp;gt;

    &amp;lt;/header&amp;gt;
    &amp;lt;div class="container"&amp;gt;
        &amp;lt;main role="main" class="pb-3"&amp;gt;
            @RenderBody()
        &amp;lt;/main&amp;gt;
    &amp;lt;/div&amp;gt;

    &amp;lt;script src="~/lib/jquery/dist/jquery.min.js"&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"&amp;gt;&amp;lt;/script&amp;gt;
    &amp;lt;script src="~/js/site.js" asp-append-version="true"&amp;gt;&amp;lt;/script&amp;gt;
    @await RenderSectionAsync("Scripts", required: false)
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;_UserNodeView.cshtml&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@inject TASK_1._1.Context.ApplicationDbContext context
@model UserModel
@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}

&amp;lt;table border="1" class="text-center"&amp;gt;
    &amp;lt;a&amp;gt; @Model.userName &amp;lt;/a&amp;gt;
        &amp;lt;tr&amp;gt;
            &amp;lt;td&amp;gt;
            @if (Model.leftMember.Equals(""))
                {
                    &amp;lt;div&amp;gt;
                        &amp;lt;form asp-controller="Home" asp-action="AddMyLeftMember" method="post"&amp;gt;
                        &amp;lt;button class="btn btn-primary" type="submit" asp-action="AddMyLeftMember" asp-route-userId="@Model.userId"&amp;gt; Left &amp;lt;/button&amp;gt;
                        &amp;lt;/form&amp;gt;
                    &amp;lt;/div&amp;gt;
                }
                else
                {
                    var u = context.User.Where(n =&amp;gt; n.userName == Model.leftMember).FirstOrDefault();
                    @Html.Partial("_UserNodeView", u)
                }
            &amp;lt;/td&amp;gt;

            &amp;lt;td&amp;gt;
            @if (Model.rightMember.Equals(""))
                {
                    &amp;lt;div&amp;gt;
                        &amp;lt;form asp-controller="Home" asp-action="AddMyRightMember" method="post"&amp;gt;
                        &amp;lt;button class="btn btn-primary" type="submit" asp-action="AddMyRightMember" asp-route-userId="@Model.userId"&amp;gt; Right &amp;lt;/button&amp;gt;
                        &amp;lt;/form&amp;gt;
                    &amp;lt;/div&amp;gt;
                }
                else
                {
                    var u = context.User.Where(n =&amp;gt; n.userName == Model.rightMember).FirstOrDefault();
                    @Html.Partial("_UserNodeView", u)
                }
            &amp;lt;/td&amp;gt;
        &amp;lt;/tr&amp;gt;

&amp;lt;/table&amp;gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Controller&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace TASK_1._1.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger&amp;lt;HomeController&amp;gt; _logger;
        private readonly ApplicationDbContext context;

        public HomeController(ILogger&amp;lt;HomeController&amp;gt; logger, ApplicationDbContext context)
        {
            _logger = logger;
            this.context = context;
        }

        public IActionResult Index()
        { 
            List&amp;lt;UserModel&amp;gt; users = context.User.ToList();

            string name = User.Identity.Name;

            if(name == null || name.Equals(""))
            {
                name = "admin";
            }

            List&amp;lt;UserModel&amp;gt; newUserList = users.Where(user =&amp;gt; String.Compare(user.userName, User.Identity.Name) &amp;gt;= 0).ToList();
            return View(newUserList);

        }

        public async Task&amp;lt;IActionResult&amp;gt; addMyLeftMember(int userId)
        { 
            TempData["LeftMemberUserId"] = userId;
            return RedirectToAction("RegisterLeftMember");
        }

        public async Task&amp;lt;IActionResult&amp;gt; addMyRightMember(int userId)
        {
            TempData["RightMemberUserId"] = userId;
            return RedirectToAction("RegisterRightMember");
        }

        public async Task&amp;lt;IActionResult&amp;gt; AddMemberLeft(UserModel userModel)
        {

            UserModel usr = context.User.Where(n =&amp;gt; n.userName == userModel.userName).FirstOrDefault();

            if(usr != null)
            {
                return Content("user already exist");
            }

            int userID = int.Parse(TempData["LeftMemberUserId"].ToString());
            var findingDaddy = context.User.Where(n =&amp;gt; n.userId == userID).FirstOrDefault();


            findingDaddy.leftMember = userModel.userName;

            context.User.Add(userModel);
            await context.SaveChangesAsync();

            return RedirectToAction("Index");
        }

        public async Task&amp;lt;IActionResult&amp;gt; AddMemberRight(UserModel userModel)
        {

            UserModel usr = context.User.Where(n =&amp;gt; n.userName == userModel.userName).FirstOrDefault();

            if (usr != null)
            {
                return Content("user already exist");
            }

            int userID = int.Parse(TempData["RightMemberUserId"].ToString());
            var findingDaddy = context.User.Where(n =&amp;gt; n.userId == userID).FirstOrDefault();

            findingDaddy.rightMember = userModel.userName;

            context.User.Add(userModel);
            await context.SaveChangesAsync();

            return RedirectToAction("Index");
        }

        public IActionResult RegisterLeftMember()
        {
            return View();
        }

        public IActionResult RegisterRightMember()
        {
            return View();
        }

        public IActionResult Login()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        [HttpPost]
        public async Task&amp;lt;IActionResult&amp;gt; Auth(string username, string password)
        {

            var findingFeni = context.User.Where(n =&amp;gt; n.userName == username &amp;amp;&amp;amp; n.password == password).FirstOrDefault();

            if(findingFeni == null)
            { 
                return Content("user or password is incorrect");
            }

            var claims = new List&amp;lt;Claim&amp;gt;
            {
                new Claim(ClaimTypes.Name, username)
            };

            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var authProperties = new AuthenticationProperties
            {

            };

            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity), authProperties);

            return RedirectToAction("Index");

        }

    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Default User&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3tmgjb9fb10o9sxfaj1z.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3tmgjb9fb10o9sxfaj1z.png" alt="Image description" width="800" height="113"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;User with Child Nodes&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn4pb4oizkoxu4m64bx53.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn4pb4oizkoxu4m64bx53.png" alt="Image description" width="800" height="117"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Final View&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fle32u0q173gqmtb9b19r.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fle32u0q173gqmtb9b19r.png" alt="Image description" width="800" height="248"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;That's all for today.&lt;/p&gt;

&lt;p&gt;And also, share your favourite web dev resources to help the beginners here!&lt;/p&gt;

&lt;p&gt;Connect with me:@ &lt;a href="https://www.linkedin.com/in/iamgaurav110/" rel="noopener noreferrer"&gt;LinkedIn &lt;/a&gt;and checkout my &lt;a href="https://main--gaurav-nandankar-dev.netlify.app/" rel="noopener noreferrer"&gt;Portfolio&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>ui</category>
    </item>
    <item>
      <title>Serilog Integration in .NET</title>
      <dc:creator>Gaurav</dc:creator>
      <pubDate>Mon, 05 Aug 2024 14:01:38 +0000</pubDate>
      <link>https://forem.com/gaurav-nandankar/serilog-integration-in-net-blp</link>
      <guid>https://forem.com/gaurav-nandankar/serilog-integration-in-net-blp</guid>
      <description>&lt;p&gt;Serilog is a newer logging framework for . NET. It was built with structured logging in mind. It makes it easy to record custom object properties and even output your logs to JSON.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How to install Serilog via Nuget and get started&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Starting with Serilog is as easy as installing a Serilog Nuget package. You will also want to pick some logging sinks to direct where your log messages should go, including the console and a text file.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Install-Package Serilog&lt;/code&gt;&lt;br&gt;
&lt;code&gt;dotnet add package Serillog.ASPNetCore&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;If you want to store the logs in file&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Install-Package Serilog.Sinks.File&lt;/code&gt;&lt;br&gt;
&lt;code&gt;dotnet add package Serillog.Sinks.File&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Create a Service Class for Configuring the Serillog&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static class AppExtension
{
    public static void SerilLogConfiruation( this IHostBuilder host )
    {
        host.UseSerillog((context, loggerConfig)=&amp;gt; {
            loggerConfig.WriteTo.Console();

                        //store logs in json format
            loggerConfig.WriteTo.File(new JsonFormatter(),"logs/applogs.txt");

                        //store logs in text format
            //loggerConfig.WriteTo.File("logs/applogs.txt");

        }),
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Add Serillog in Program.cs&lt;/p&gt;

&lt;p&gt;&lt;code&gt;builder.Host.SerillogConfiguration();&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[ApiController]
[Route("[controller]")]
public class DemoController : ControllerBase 
{
    private readonly ILogger&amp;lt;DemoController&amp;gt; _ilogger;

    public DemoController(ILogger&amp;lt;DemoController&amp;gt; logger)   
    {
        _ilogger = logger;
    }

    [Https]
    public IEnumerable&amp;lt;string&amp;gt; Get() 
    {
        _logger.LogInformation("Demo Controller Get is Called");
        return null;
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>dotnet</category>
      <category>csharp</category>
      <category>serillog</category>
    </item>
    <item>
      <title>Reset Firebase User Password in C# Using Firebase SDK</title>
      <dc:creator>Gaurav</dc:creator>
      <pubDate>Thu, 01 Aug 2024 05:50:58 +0000</pubDate>
      <link>https://forem.com/gaurav-nandankar/resetting-a-firebase-user-password-in-c-using-firebase-sdk-4p9g</link>
      <guid>https://forem.com/gaurav-nandankar/resetting-a-firebase-user-password-in-c-using-firebase-sdk-4p9g</guid>
      <description>&lt;p&gt;In this guide, we'll walk through the process of resetting a user's password in a C# application using the Firebase SDK. This functionality is essential for providing a smooth user experience, allowing users to recover their accounts in case they forget their passwords&lt;/p&gt;

&lt;p&gt;Firebase Authentication provides an easy way to integrate user authentication into apps. It supports various sign-in methods like email/password, phone number, and social media accounts. Users can manage their passwords and receive email verification. The service ensures secure authentication and integrates well with other Firebase tools&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Set Up Firebase SDK:&lt;/strong&gt; &lt;br&gt;
Make sure you have the Firebase SDK installed and configured in your C# project. You can add it via NuGet Package Manager.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fttvilj5gl50x75qpafnr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fttvilj5gl50x75qpafnr.png" alt="Image description" width="800" height="217"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Initialize Firebase:&lt;/strong&gt; &lt;br&gt;
Ensure that your Firebase application is initialized correctly with the required credentials. Navigate to Below Service Accounts as Method in Below Image and Click on Generate New Private Key to get it will give you a .json file which contains the Firebase credentials.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fat1htalxfr601vpxsb5n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fat1htalxfr601vpxsb5n.png" alt="Image description" width="800" height="104"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace demo.Services.Implementation
{
    public class Service : IService
    {  
        private readonly FirebaseAuth _firebaseAuth;

        public Service(IHTTPService httpService)
        { 
            _httpService = httpService;

            var FilePath = Path.Combine(Directory.GetCurrentDirectory(), "Firebase/your-json-file-name.json");


         // Check if the default FirebaseApp instance already exists
         if (FirebaseApp.DefaultInstance == null)
         {
             FirebaseApp.Create(new AppOptions()
             {
                 Credential = GoogleCredential.FromFile(FilePath)
             });
         }
            _firebaseAuth = FirebaseAuth.DefaultInstance;
        }

        public async Task resetPassword(string Email, string newPassword)
        {

            var uid = await getUID(Email);

            var userRecordArgs = new UserRecordArgs()
            {
                Uid = uid,
                Password = newPassword,
            };

            await _firebaseAuth.UpdateUserAsync(userRecordArgs);
        }

        public async Task&amp;lt;string&amp;gt; getUID(string email)
        {
            var userRecord = await _firebaseAuth.GetUserByEmailAsync(email);
            return userRecord.Uid;
        }

    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Conclusion:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Integrating Firebase Authentication into your C# application to handle password resets is a straightforward process that significantly enhances the user experience. By following the steps outlined in this guide, you can provide a secure and efficient way for users to recover their accounts. The Firebase SDK offers robust support for various authentication methods, ensuring seamless integration with your application. Remember to keep your Firebase credentials secure and regularly update your application's dependencies to maintain security and functionality. With these practices in place, you can confidently manage user authentication and password recovery in your C# applications.&lt;/p&gt;

</description>
      <category>firebase</category>
      <category>csharp</category>
    </item>
  </channel>
</rss>
