Friday, 12 November 2021

Use multiple implementations of an interface with ASP.NET Core DI

 On my previous article Middleware and Filters power in ASP.NET Core, one of my friend requested me to write about multiple implementations of an interface dependency resolution and I promised him that my next article will cove this. So here it is.

In this article, I’ll be using the same example by extending it to use multiple implementation of logger service by resolving it based on a config setting to log my exception.

First we will create ILoggerService and different implementation of it by creating a Services folder in the project.

namespace CoreWebAPIDemo.Services
{
public enum LogType
{
Trace,
Debug,
Information,
Warning,
Error
}
public interface ILoggerService
{
public void Log(LogType logType, object logInfo);
}
public class NullLoggerService : ILoggerService
{
public void Log(LogType logType, object logInfo)
{
//Do Nothing
}
}
public class SerilogFileLoggerService : ILoggerService
{
public void Log(LogType logType, object logInfo)
{
//your logging code
}
}
public class DbLoggerService : ILoggerService
{
public void Log(LogType logType, object logInfo)
{
//your logging code
}
}
}

Next, I’ll add a delegate to hold a reference of a function which accept the one string argument ‘logger type’ and return the ILoggerService instance. For this create a cs file “LoggerServiceResolver.cs” and add below code.

namespace CoreWebAPIDemo.Services
{
public delegate ILoggerService LoggerServiceResolver(string loggerType);
}

Now in Startup.ConfigureServices method, add the different logger services and also add LoggerServiceResolver with an implementation to find the right requested service.

services.AddScoped<SerilogFileLoggerService>();
services.AddScoped<DbLoggerService>();
services.AddScoped<NullLoggerService>();
services.AddTransient<LoggerServiceResolver>(serviceProvider => loggerType =>
{
switch (loggerType)
{
case "SerilogFileLogger":
return serviceProvider.GetService<SerilogFileLoggerService>();
case "DbLogger":
return serviceProvider.GetService<DbLoggerService>();
default:
return serviceProvider.GetService<NullLoggerService>();
}
});

I want to set the logger type option configurable through appsettings.json file so will add a setting there as:

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"UserLogger": "SerilogFileLogger",
"AllowedHosts": "*"
}

By this implementation is ready. Now we need to add the code to consume this and for that I’ll enhance my “ExceptionHandlingMiddleware” which I use in my previous article. Please read it here: Middleware and Filters power in ASP.NET Core

using CoreWebAPIDemo.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System;
using System.Net;
using System.Threading.Tasks;
namespace CoreWebAPIDemo.Middleware
{
public class ExceptionHandlingMiddleware
{
private readonly LoggerServiceResolver _serviceResolver;
private readonly IConfiguration _configuration;
private readonly RequestDelegate _requestDelegate;public ExceptionHandlingMiddleware(RequestDelegate requestDelegate, IConfiguration configuraiton, LoggerServiceResolver serviceResolver)
{
_requestDelegate = requestDelegate;
_serviceResolver = serviceResolver;
_configuration = configuraiton;

}
public async Task Invoke(HttpContext context)
{
try
{
await _requestDelegate(context);
}
catch (Exception ex)
{
await HandleException(context, ex);
}
}
private Task HandleException(HttpContext context, Exception ex)
{
var logType = _configuration.GetValue<string>("UserLogger");
var myLogger = _serviceResolver(logType);
myLogger.Log(LogType.Error, ex);

context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return context.Response.WriteAsync(ex.Message);
}
}
}

In above code, Code in Bold is the new code added and needed for this example. Now we all set to use the different implementations of ILoggerService with ASP.NET Core DI with my middleware. Similarly we can implement the same with “ExceptionHandlerFilter” class and changes would be (highlighted in Bold):

using CoreWebAPIDemo.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;
using System;
using System.Net;
namespace CoreWebAPIDemo.Middleware
{
public class ExceptionHandlerFilter : Attribute, IActionFilter
{
private readonly LoggerServiceResolver _serviceResolver;
private readonly IConfiguration _configuration;
public ExceptionHandlerFilter(IConfiguration configuraiton, LoggerServiceResolver serviceResolver)
{
_serviceResolver = serviceResolver;
_configuration = configuraiton;
}
public void OnActionExecuting(ActionExecutingContext context) { }public void OnActionExecuted(ActionExecutedContext context)
{
var logType = _configuration.GetValue<string>("UserLogger");
var myLogger = _serviceResolver(logType);


if (context.Exception is Exception exception)
{
myLogger.Log(LogType.Error, exception);
context.Result = new ObjectResult(exception.Message)
{
StatusCode = (int)HttpStatusCode.InternalServerError,
};
context.ExceptionHandled = true;
}
}
}
public class HttpResponseException : Exception
{
public int Status { get; set; } = 500;
public object Value { get; set; }
}
}

Thank you for reading. Hope you enjoyed it and learn the Use of multiple implementations of an interface with ASP.NET Core DI. Don’t forget to clap if you like it and follow me to receive such article updates from me.

Thursday, 11 November 2021

Middleware and Filters power in ASP.NET Core

 In ASP.NET core, Middleware and Filters are two concepts which are very useful & powerful but often confuses also on which one to choose.

Middleware and Filters serves similar purpose and both can be used to achieve the common tasks like exception handling, localizations, authentications etc… but both has certain difference in a way it works with the pipeline.

Lets understand the difference and use of Middleware and Filters through an example of Exception Handling.

Middleware allows in the pipeline to handle requests and responses Where you can choose if the component “is to pass the request to the next component in the pipeline” or “can perform work before and after the next component in the pipeline”. i.e. Perform request validation, localization, exception handling or logging each request and response etc.

Filters run within the ASP.NET Core action invocation pipeline and allows to perform certain operation before or after specific stages in the request processing pipeline. i.e. Perform authentication or authorization to validate requested action processing.

Now lets understand it with the example of Exception Handling generically using both the way.

Scenario: Handle all unhandled exception in code to safeguard the crucial information about code to be delivered to the end user.

Note: ASP.NET Core has already predefined middleware to achieve the same but we are doing it manually to get more control on it.

1. Using Middleware.

Here we try to handle all uncaught exception through out the application through a middleware we create. Middleware is a normal class so you don’t have to inherit any interface/specific class but your class must have the method called Invoke “public async Task Invoke(HttpContext context)”.

using Microsoft.AspNetCore.Http;
using System;
using System.Net;
using System.Threading.Tasks;
namespace CoreWebAPIDemo.Middleware
{
public class ExceptionHandlingMiddleware
{
public RequestDelegate requestDelegate;
public ExceptionHandlingMiddleware(RequestDelegate requestDelegate)
{
this.requestDelegate = requestDelegate;
}
public async Task Invoke(HttpContext context)
{
try
{
await requestDelegate(context);
}
catch (Exception ex)
{
await HandleException(context, ex);
}
}

private static Task HandleException(HttpContext context, Exception ex)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return context.Response.WriteAsync(ex.Message);
}
}
}

In above code here I have RequestDelegate dependency resolving code to handle the http request because my requirement to catch the unhandled exception in the pipeline . Now lets add an extension method for IApplicationBuilder to simplify the call for this middleware.

using Microsoft.AspNetCore.Builder;namespace CoreWebAPIDemo.Middleware
{
public static class ExceptionHandlerMiddlewareExtension
{
public static IApplicationBuilder UseExceptionHandlerMiddleware(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<ExceptionHandlingMiddleware>();
}

}
}

Our Middleware to catch the uncaught exception is ready and now we need to register it to request pipeline which will be from Startup.Configure method. Here we have to be very careful as the pipeline order is driven through the order of middleware services you add. In this we need to catch the exception while processing the request hence I’ll be adding this middleware at the end just before the UseEndpoints middleware call.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseRouting(); app.UseStaticFiles(); app.UseCors("AllowAll"); app.UseExceptionHandlerMiddleware(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

and finally to test the code, lets create a control which will throw the exception.

using Microsoft.AspNetCore.Mvc;
using System;
namespace CoreWebAPIDemo.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class HomeController : ControllerBase
{
[HttpGet]
public IActionResult Index(int value)
{
if (value == 1)
return Ok("I'm Happy");
else
throw new Exception("I didn't like your number");
}
}
}

output would be:

Now lets do the exception handling through action filter.

2. Using Filter.

Here we will create a action filter which inherits IActionFilter.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Net;
namespace CoreWebAPIDemo.Middleware
{
public class ExceptionHandlerFilter : Attribute, IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context) { }
public void OnActionExecuted(ActionExecutedContext context)
{
if (context.Exception is Exception exception)
{
context.Result = new ObjectResult(exception.Message)
{
StatusCode = (int)HttpStatusCode.InternalServerError,
};
context.ExceptionHandled = true;
}
}
}

}

In this case, we are adding code to handle exception OnActionExecute method which will get executed after the action is executed.

Now we need to register it through Startup.ConfigureServices method if we want to apply it forcefully to all the controller’s action execution and here we can add this anywhere in the method without worrying about the order.

services.AddControllers(options => options.Filters.Add(new ExceptionHandlerFilter()));

Or we can also restrict it to a specific controller or action method and this is one big advantage over using Middleware concept to handle exceptions like in this scenario. Also when we reach here our MVC context is fully ready like model binding and all is done and available with the context.

And this is the reason, I have also inherited Attribute class while creating ExceptionHandlerFilter. Now here is the code to use it with the specific controller only.

using CoreWebAPIDemo.Middleware;
using Microsoft.AspNetCore.Mvc;
using System;
namespace CoreWebAPIDemo.Controllers
{
[ApiController]
[Route("api/[controller]")]
[ExceptionHandlerFilter]
public class HomeController : ControllerBase
{
[HttpGet]
public IActionResult Index(int value)
{
if (value == 1)
return Ok("I'm Happy");
else
throw new Exception("I didn't like your number");
}
}
}

Note: Don’t forget to comment the earlier middleware code for registering “app.UseExceptionHandlerMiddleware();” in case if you are in same project like me while testing.

Bonus Reading

ASP.NET core also provides predefined middleware for exception handing which you can use to control the information flowing to the use in case of uncaught exception or error and you can achieve that by doing this:

  1. Create an ErrorController and two action method as below to handle development and production scenario.
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
namespace CoreWebAPIDemo.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class ErrorController : ControllerBase
{
/// <summary>
/// The preceding Error action sends an RFC 7807-compliant payload to the client.
/// </summary>
/// <returns></returns>
[Route("/error")]
public IActionResult Error() => Problem("Oops there is a problem. Excuse me and smile!");
[Route("/error-local-development")]
public IActionResult ErrorLocalDevelopment(
[FromServices] IWebHostEnvironment webHostEnvironment)
{
if (webHostEnvironment.EnvironmentName != "Development")
{
throw new InvalidOperationException("Ugggh! This is not for Production, go away.");
}
var context = HttpContext.Features.Get<IExceptionHandlerFeature>();return Problem(
detail: context.Error.StackTrace,
title: context.Error.Message);
}
}
}

2. Enable ASP.NET Core predefined ExceptionHandler middleware from Startup.Configure method.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseExceptionHandler("/error-local-development");
}
else
{
app.UseExceptionHandler("/error");
}
app.UseHttpsRedirection(); app.UseRouting(); app.UseStaticFiles(); app.UseCors("AllowAll"); app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

Thank you for reading. Hope you enjoyed it and learn the use of Middleware and Filter concept of ASP.NET Core. Don’t forget to clap if you like it and follow me to receive such article updates from me.

Monday, 25 October 2021

Unable to ping host.docker.internal

 This is the problem people out there facing a lot where their docker containers are unable to connect to docker host.

In general, host IP will be changing specially in dev machine and this create trouble for docker to resolve the host DNS and establish the connection. Hence Docker recommend a special DNS name host.docker.internal to use which resolves to the internal IP address used by the host.

In windows, we need to add below entry to the C:\Windows\System32\drivers\etc\hosts file as:
192.XXX.XX.XX host.docker.internal

All good but there is a problem where docker containers are unable to ping host.docker.internal and I too face the problem every time I restart the system. There is a huge discussion here and the channel is closed and I don’t see a working solution.

After struggling a lot, finally I figured out a working solution for me which I’m using it since last one month from the date I’m writing this post. Solution is, run the below command once when you restart your system, basically it is a cleanup command to clean unused resources like unused network, cache, unused & dangling containers. Read here more about this.

docker system prune

My Environment:
OS: Windows 10 Enterprise
Docker Desktop Version: 4.1.1

Hope this helps you. Thank you for reading.

Notification Queue : RabbitMQ in .NET Core

 Based on my previous article about RabbitMQ in .Net Core, one of my friend asked me a question that How He can build the Notification feature (bell icon, which we generally see with many applications and with medium too) using RabbitMQ which to publish the user specific notification message.

I said, well it is very easy and all you have to do is: publish the message to a specific queue with a routing queue and exchange type “direct”: publish message to the queues whose binding key exactly matches the routing key of the message.

Note: In my previous article I didn’t mention the exchange type and in result it was using default exchange type as “fan out”: publish messages to all the queues bound to it.

First lets start the RabbitMQ server running in docker container. If you don’t have already, it will pull by default and command it:

docker run -it --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3.9-management

Now we will create the Publisher/Sender and here is the complete code:

using RabbitMQ.Client;
using System;
using System.Text;
namespace RabbitMQPublisher
{
class Sender
{
static void Main(string[] args)
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
Console.WriteLine("Enter command 'exit' to stop sending meesages");
string message = string.Empty;
string receiver = string.Empty;
do
{
SendMessage(connection, message, receiver);
Console.Write("Enter your message:");
message = Console.ReadLine();
Console.Write("Enter the reciever:");
receiver = Console.ReadLine();

} while (!message.Equals("exit", StringComparison.OrdinalIgnoreCase));
}
}
private static void SendMessage(IConnection connection, string message, string receiver)
{
if (string.IsNullOrEmpty(message))
return;
using (var channel = connection.CreateModel())
{
//Create the exchange type direct which will broadcast messages to a specific queue driven by routingKey.
channel.ExchangeDeclare(exchange: "direct_msg", type: "direct");
channel.QueueDeclare(queue: "Notification",durable: false, exclusive: false, autoDelete: false, arguments: null);var body = Encoding.UTF8.GetBytes(message);var properties = channel.CreateBasicProperties();
properties.Persistent = true;
channel.BasicPublish(exchange: "direct_msg",routingKey: receiver,
basicProperties: properties,
body: body);

Console.WriteLine($" Message Sent to '{receiver}'");
}
}
}
}

In above code, receiver name is an input and based on that code creates a routingKey as “{receiver_name}” input and bind it to the queue “Notification” with exchange type as “direct”. Rest all is same as per my previous article.

Next, we will create Receivers/Subscribers. Here is the complete code:

using RabbitMQ.Client;
using RabbitMQ.Client.Events;

using System;
using System.Text;
namespace RabbitMQSubscriber
{
class Receiver
{
public static void Main()
{
var queueName = "Notification";
Console.Write("Enter UserName:");
string userName = Console.ReadLine();
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.ExchangeDeclare(exchange: "direct_msg", type: "direct");
channel.QueueDeclare(queue: queueName, durable: false, exclusive: false, autoDelete: false, arguments: null);
channel.QueueBind(queue: queueName, exchange: "direct_msg", routingKey: userName);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
Console.WriteLine($"Message Received: {message}");
channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
};
//making autoAck: false as we are doint it manually above
channel.BasicConsume(queue: queueName, autoAck: false, consumer: consumer);
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
}
}
}
}

In above Receiver’s code, routing key is set to the user input {user_name} and bind it to the queue named “Notification” and exchange type is “direct”. That’s all, now if you run the both the application as One instance of Sender and multiple instances of Receiver then the output would be as below:

Thank You for reading. Happy Happy RabbitMQueuing.

Monday, 18 October 2021

RabbitMQ in .NET Core

 RabbitMQ is a most popular and widely used open source message broker software. It supports multiple protocols AMQP, STOMP, MQTT, HTTP and WebSockets. Read more about these protocols here.

RabbitMQ is lightweight and can be easily deployed on premises and in the clouds. RabbitMQ is available on Microsoft azure as “RabbitMQ Server” as well as “RabbitMQ as a Service”. It also supports container based hosting environment and I love it and this is what I’m gonna explain here that How easy it is to make it running.

Before we start, you would need Docker Desktop application running on your system. Once you have the docker desktop application, switch to Linux containers and follow the below steps to write your first simple RabbitMQ message brokering application.

Step 1: Pull and host the docker image. Open the powershell command prompt and run the command:

docker run -it --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3.9-management

Above command will run host the docker rabbitmq image under localhost:5672 port which uses amqp protocol and the rabbitmq management portal under localhost:15672 which uses http protocol.

Test the RabbitMQ server by browsing rabbitmq management portal: http://localhost:15672/#/

Note: the default userid and password of the portal would be “guest” and “guest”.

Step 2: We are all set with RabbitMQ server hence Lets begin with simple sender and receiver application. Sender will publish a message to a queue and receiver will read it from the same queue.

For this, Lets create two simple .Net 5 console application and name it RabbitMQSender and RabbitMQReceiver.

Step 3: Install RabbitMQ.Client nuget package from nuget store.

Step 3: Now Use the below code to create the sender under RabbitMQSender project which will publish messages to a queue named “hello”.

using RabbitMQ.Client;
using System;
using System.Text;
namespace RabbitMQSender
{
class Sender
{
static void Main(string[] args)
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
Console.WriteLine("Enter command 'exit' to stop sending meesages");
string message = string.Empty;
do
{
SendMessage(connection, message);
Console.Write("Enter your next message:");
message = Console.ReadLine();
} while (!message.Equals("exit", StringComparison.OrdinalIgnoreCase));
}
}
private static void SendMessage(IConnection connection, string message)
{
if (string.IsNullOrEmpty(message))
return;
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "hello",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
var body = Encoding.UTF8.GetBytes(message);var properties = channel.CreateBasicProperties();
properties.Persistent = true;
channel.BasicPublish(exchange: "",
routingKey: "hello",
basicProperties: properties,
body: body);
Console.WriteLine(" [x] Sent {0}", message);
}
}
}
}

Above code is simple where we are:
i. creating a connection factory pointing to localhost:5672 (since 5672 is default reserved port for RabbitMQ hence we don’t need to mention in the code as hostname).
ii. establish the connection (var connection = factory.CreateConnection()).
iii. create the channel, session and model (var channel = connection.CreateModel()).
iv. Declare a queue where message will be published (channel.QueueDeclare).
v. publish the message (channel.BasicPublish).

To make sure the message will be delivered to the receiver whenever he comes i’m making it persistent. Properties will also allows you to define the contentType, ContentEncoding, DeliveryMethod, Expiraiton etc.

var properties = channel.CreateBasicProperties();properties.Persistent = true;

Step 4: Use the below code to create the receiver under RabbitMQReceiver project.

using RabbitMQ.Client;
using RabbitMQ.Client.Events;

using System;
using System.Text;
namespace RabbitMQReceiver
{
class Receiver
{
public static void Main()
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "hello",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(" [x] Received {0}", message);
channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
};
channel.BasicConsume(queue: "hello",
autoAck: false,//making it false as we are doing it manually above
consumer: consumer);
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
}
}
}
}

Here too we are following the same process till creating the channel, session and model then declaring the queue. This will be having the same queue which you named for the sender’s queue as this has to listen the message for the same queue.

Once above is done we create the consumer and add the consumer’s Received event and that is where we read the published messages from sender and send back a acknowledgment to the sender. Here instead of RabbitMQ default message acknowledgment feature, I’m doing it manually after I read the message.

channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);

Now you can run both the program and test it. you can run multiple Receivers at a time and RabbitMQ will deliver the message to the active receivers one at a time based on default Round Robin method.

Note: if you would have noticed, I have used exchange=”” publishing the message in sender and it used RabbitMQ’s default Direct exchange protocol which publish the method to one queue at a time. if we need to publish the message for multiple queues then we need to user other exchange protocol as “Topic” or “Fanout”.

Thanks for reading. Happy RabbitMQueuing.