Archive for the ‘.NET’ Category

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.

    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.

    Local Functions in C#7.0

    Posted: July 30, 2017 in .NET, C#
    Tags: ,

    The nested functions (methods) or local functions are functions defined inside another function , referred to as the enclosing function. The nested functions are available only within the scope of the enclosing functions. This is nothing new. The nested functions has been there in languages like ALGOL , PASCAL , Lisp , JavaScript for quite sometime and even in modern programming languages like Scala.

    Can we do similar stuff in C#?

    image

    Suppose in the snippet above we want to extract out the computation logic in a separate function. A quick way will be to extract it out to separate private function. But that will be bit confusing, because the scope of the private method will not be restricted to the method Calculate and it will be a class level method. So someone reading the code later, will have difficulty to understand, that my intent was to have this private method only to be used by the Calculate method.

    One way of doing this will be to define an anonymous method within the Calculate method. But here I have to define a delegate (type definition) and create a delegate object (first class object in itself) to cater to my simple need of having just a helper function.

    image

    C#7.0 helps us to achieve this with the feature of local functions , another syntactic sugar coat and added compile time checks. The code below shows how we can define nested local function within another method in C#7.0.

    image

    This local function gets compiled into a compiler generated private method as shown below, without adding any added overhead.

    image

    image

    Deconstruction in C#7.0

    Posted: July 29, 2017 in .NET, C#
    Tags: , ,

    In my earlier blog post related to Tuples, I had used the following two ways for accessing the elements of the tuple.

    image

    image

    The first one is obviously inefficient and to be honest wrong, there is no point calling the method twice. The second one can be simplified further as shown in the snippet below:

    image 

    This is referred to as the deconstruction of the tuple.

    This technique of deconstruction can be now applied to any . NET class/struct , by implementing the Deconstruct method.

    image

    The object instance can be then deconstructed back into three variables as shown below:

    image

    The code shown above is nothing but the syntactic sugar coat. The decompiled code clearly shows the Deconstruct method of the Person class getting invoked and the variables a , b & c does not exists in the complied code. These are replaced by variables declared with names same as the parameters of the Deconstruct method implementation.

    image