In the last post we have discussed the basics of ASP.NET Core Middleware and how it fits into the request processing pipeline. As a next step we will see how we can build the middleware pipeline using request delegates that contain our custom code.

These request delegates are configured in the Configure method of the Startup class. The three extension methods of IApplicationBuilder that are used to build and configure the middleware pipeline are as follows:

  • Run – This method add a request delegate in the pipeline which terminates the middleware pipeline.
  • Use – This method adds a request delegate in the middleware pipeline which processes the request and passes it onto the next delegate in chain. Similarly processes the response and passes onto the previous delegate in chain (if any).
  • Map – This method which branches the middleware pipeline based on the request path and invokes the appropriate delegate based on path provided.

Let’s take a bit deeper look into each of these extension methods.

Run

The signature of this method is as shown below:

image

This method configures a delegate which accept HttpContext as input and returns a Task object. It terminates the middleware pipeline by generating the response as shown below:

image

The output displayed in the console will be as expected:

image

The page will display a simple text output as shown below. This is because the middleware pipeline is terminated by this delegate and none of the MVC related components gets executed.

image

Use

The signature of this method is as shown below:

image

The code snippet below shows how the Use method can be used to chain the middleware components.

image

The output messages in the console will be in the following sequence:

image

Map

The method signature is as follows:

image

Then we have implemented two methods with IApplicationBuilder as input parameter as shown below:

image

The Map methods are called as shown below:

image

When I am accessing http://localhost:5000, the two request delegates added using the two Use methods and then the request delegate in the Run method is invoked.

image

When I am accessing http://localhost:5000/map1, the two request delegates added using the two Use methods and then the request delegate in the HandleMap1 method is invoked.

image

When I am accessing http://localhost:5000/map2 , the two request delegates added using the two Use methods and then the request delegate in the HandleMap2 method is invoked.

image

Memoization Using C#

Posted: April 5, 2020 in .NET, C#
Tags: , ,

Memoization is a technique very commonly used in Functional Programming to improve the performance of a function execution by caching its results. Here, caching helps to avoid the expensive computations of a complex function.

Before getting into the implementation which in my opinion is pretty straightforward to understand let put in few lines on the term itself. This activity of caching the results is similar to memorizing the already computed results but then why “r” is missing and its called memoization ? This is because the term has been derived from memo which is an American English for the Latin word memorandum. So it’s memo-ization.

In order to this we normally write a Higher Order Function (HOF) which accepts the function to be memoized as input and returns a closure of same as type as the input function and wraps it within the logic for caching as shown in the sample below:

image

Now let’s try to invoke this function. We will use a simple factorial function for memoization here.

image

We are making three calls to the memoized version of the Factorial function, the last call is made with a repeated parameter.

image 

For the first two calls the function will be executed and the results of the third call are picked up from the cache.

image

We can write the Memoize function in a much more concise manner as shown below:

image

We can also make the function thread-safe using ConcurrentDictionary for caching.

image

ASP.NET Core Middleware–Part 1

Posted: November 11, 2019 in .NET, C#
Tags:

In one of my earlier post, I have discussed in details about the ASP.NET Core request processing and the key components involved i.e reverse proxy, ASP.NET Core Web Server and the ASP.NET Core infrastructure and application logic.

image

In this post we will take a bit more deep dive into the ASP.NET Core Infrastructure components. The flow of information for processing an incoming request and generating the response is shown in the figure below:

image

The diagram above is not a very generic one but elaborates the ASP.NET Core Infrastructure and Application Logic component into two, Middleware Pipeline and MVC Middleware. Before getting into any further details let’s try to understand what this Middleware Pipeline is all about.

In the above flow, reverse proxy receives the request and forwards the raw HTTP request to the ASP.NET Core Web Server. ASP.NET Core Web Server passes the raw HTTP request and instantiates the HttpContext object. HttpContext is a class that encapsulates all information pertaining to a HTTP request including information related to the subsequently generated HTTP response. For every incoming HTTP request there is one instance of HttpContext created and passed onto the subsequent component , the Middleware Pipeline in this case.

The ASP.NET Core Middleware is a chain of components that forms a pipeline for processing an HTTP request, generating the response and subsequent processing of the response before being passed back to the ASP.NET Core Web Server. To be more precise it does the following:

  • Accepts an incoming HTTP request , analyzes it and does some processing if required and passes the request to the next component.
  • Accepts an outgoing HTTP response, analyzes it and does some processing if required and passes the response to the previous component or, the ASP.NET Core Web Server.
  • Accepts an incoming HTTP request and generates the response and passes the response to the previous component or, the ASP.NET Core Web Server.These type of middleware components which short-circuits the pipeline i.e generates the response and passes back the response to the previous component instead of the next are called terminal middleware because it prevents the next component from processing the request.

These middleware components can perform a wide array of tasks like logging, exception handling, serving static files etc. The most important amongst these in a ASP.NET Core MVC application is the MVC Middleware which processes requests and generates the HTML and API responses. This is a terminal middleware as shown in the above figure. Similarly for requests to serve a static file , the Static File Middleware acts as the terminal middleware as shown below:

image

.NET Core provides a set of middleware components which needs to be configured through code and also has provision to develop custom middleware components.We will take a look at these in the coming posts.

    Control Expressions in Kotlin

    Posted: June 16, 2019 in Kotlin
    Tags: ,

    In any imperative programming language, an expression is a line or fragment of code that is computed to produce a value whereas statement is a standalone unit of the program which intends to perform some action. In languages like C# or Java, we have control structures for decision making , branching etc.. as statements rather than expressions.

    The following snippet shows a classic “If -Else” statement in C#.

    image

    However, this can be simplified and curly braces are not mandatory here.

    image

    But I cannot write the following in C#. This is because I cannot return a statement where a function is supposed to return an “int”.

    image

    Similar stuff can be done in C# with a ternary operator as shown below:

    image

    But as the conditional statement becomes complex, usage of a ternary operator is difficult and makes the code clumsy and kludgy.

    While playing around with Kotlin, I found that control structures like “If” , “When ( switch in C# or Java)” are expressions instead of statements and evaluates to a value. So, I can easily write the following.

    image

    This works as a simple alternative to the ternary operator. In Kotlin, there is no ternary operator as we don’t need any. But if-else expressions can be complex with multiple expressions/statements within it.In that case the last expression will be the “value” of that parent if/else expression as shown below.

    image

    Nested If-Else, If-Else-If expressions will also work in the same logic.

    Kotlin, also has statement blocks enclosed within curly braces and the following “If” block without an “Else” is treated as a statement.

    image

    In the last post we found that the Startup class in ASP.NET Core works based on convention. The runtime inspects the class through reflection and invokes the appropriate methods i.e. Configure and ConfigureServices (optional). If class is not properly implemented e.g. say Configure method is not present then there should be a runtime exception. When I removed the Configure method from the Startup class I got the following error:

    Unhandled Exception: System.InvalidOperationException: A public method named ‘ConfigureProduction’ or ‘Configure’ could not be found in the ‘startuptest.Startup’ type.

    The above message is quite as expected but it was not clear to me why runtime was looking for a method named ConfigureProduction?

    There seems to be something missing in the documentation and something else going on inside. So the best way to clear this confusion is to have a look into the ASP.NET Core codebase in github. The core logic for loading the Startup class is implemented in StartupLoader class as shown below.

    image

    Note, the last parameter environmentName. Does this ring a bell ? “ConfigureProduction”… Production…Environment.

    Let’s drill down further. Let’s concentrate on the FindConfigureDelegate method which is used to identify the Configure method of the Startup class. This method in turn invokes “FindMethod” and we need to get into the logic of “FindMethod” to understand this better.

    image

    The code snippet of FindMethod is shown below.

    image

    The steps in selecting the right method are:

    a) Look for method with name Configure{EnvironmentName}. If found, then check for overloads.In case there are overloads then throw InvalidOperationException.

    b) If there are no method with name Configure{EnvironmentName} , then look for method with name Configure.If found, then check for overloads.In case there are overloads then throw InvalidOperationException.

    c) If there are no methods found with name Configure{EnvironmentName} or Configure then throw InvalidOperationException.

    Step c) above explains the exception message we started with “Unhandled Exception: System.InvalidOperationException: A public method named ‘ConfigureProduction’ or ‘Configure’ could not be found in the ‘startuptest.Startup’ type.

    The only missing piece in the puzzle is now the environment name. ASP.NET Core environment name is stored in the environment variable “ASPNETCORE_ENVIRONMENT”. The runtime reads from this variable and sets the IHostingEnvironment.EnvironmentName property. The framework supported values for this variable are “Development” , “Staging” and “Production” , however it can accept other values as well.

    We can set this variable from the command line as

    set ASPNETCORE_ENVIRONMENT=Development2

    Now running the code without any Configure method in the Startup class will lead to the following exception message.

    Unhandled Exception: System.InvalidOperationException: A public method named ‘ConfigureDevelopment2‘ or ‘Configure’ could not be found in the ‘startuptest.Startup’ type.

    In the last post we have discussed on how the ASP.NET Core request processing pipeline works. As a next step, let’s take a closer look into how the ASP.NET Core application gets started and initialized.When we create a new ASP.NET Core application e.g. say a MVC application, we can see two files which gets added by default, Program.cs and Startup.cs as shown in the figure below:

    image

    The Program and the Startup class control startup and the configuration of the application runtime. The ASP.NET core application is just a console application and like any other.NET console application and needs a Main method as the entry point of the application.

    The Program class contains the implementation of this static void Main method which is used to create an instance of IWebHost and run the same. IWebHost is one of the key components of the application which contains the application configuration and the ASP.NET Core Web server.

    The Main method performs the initialization of the IWebHost instance and starts it as shown in the figure below:

    image

    The IWebHostBuilder is used to configure the ASP.NET Core Development Server (default is Kestrel) , Logging , IIS Integration (if required) , Content Root etc.We will take a deeper look into the IWebHost / IWebHostBuilder later.

    Now let’s take a look into the Startup class which gets wired into the IWebHost instance as highlighted below:

    image

    UseStartup is a generic extension method on IWebHostBuilder as shown below. But the interesting point to be noted here is the generic type parameter has no constraints TStartup can be any class.

    image

    This is quite interesting as I am more used to having an interface driven strongly typed parameters in this kind of situations. It’s quite obvious that this Startup class needs to work in tandem with the IWebHost based on certain conventions. Now let’s take a look at the code that is in the Startup class by default.

    image

    a) The Configure method is a must have for the Startup class. This is invoked by the runtime host, which creates an instance of IApplicationBuilder and passes it as an agrument.This IApplicationBuilder is used to configure the middleware pipeline by adding suitable components. The other parameter IHostingEnvironment can be omitted if not required. We will get into further details of the IApplicationBuilder interface while exploring the ASP.NET Core middleware pipeline.

    b) The ConfigureServices method is optional.This can be implemented to add additional services to the IServiceCollection.We will get into further details of the IServiceCollection interface while exploring the ASP.NET Core Dependency Injection.

    Now comes the question, is it a good design, making the startup class work by convention rather than having any strongly typed interface. I think it’s fine. It helps to keep things simple. This is the startup code so we can take up the additional overhead of reflection in inspecting the method definitions and then invoking it. Also, the chances of type mismatch or method mismatch is not there because its the startup code used to configure and initialize the application and should not have a widely varying behavior at runtime. This is also more flexible as we can different other parameters in the methods to suit our needs.

    Next comes the question why we have two classes for the application initialization, Program and Startup? The segregation of responsibilities is very clear, the Program class contains initialization code that is used to set up the infrastructure that will rarely change over the lifetime of the project (like ASP.NET Core Web Server, Logging etc.) whereas Startup contains the initialization of features that are required to customize the application’s behavior.