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.

Advertisements

ASP.NET Web Forms were launched as part of .NET Framework 1.0 in 2002. It was a logical evolution from ASP, moving away from interpreted web pages with dependency on a scripting engine, towards type safe and compiled web pages model with more well structured code. ASP.NET Web Forms offered developers with a event based programming model, which helped to create web applications quickly. But over time, we found certain limitations of this framework in developing and maintaining large web applications.This was mostly due to lesser control on the generated HTML , poor testability and an artificial/complex stateful model as opposed to the stateless nature of the web.

ASP.NET MVC was released around 2009 which was based on the Model-View-Controller architectural pattern leading to clean separation of concerns, improved testability and more tighter control on HTML. This was more in line with other popular frameworks of the time like Ruby-On-Rails etc.

However , both ASP.NET Web Forms and ASP.NET MVC were built on the same underlying framework and relied heavily on features provided by System.Web.dll. This assembly is a part of the .NET Framework and explicitly coupled with Windows Web Server i.e. Internet Information Services., IIS. Also, the heavy dependency on this assembly made changes to ASP.NET complex and release cycles slow.

The key goals of ASP.NET Core was to make the framework cross platform and the overall architecture more modular. So, clean separation of the web server from the web application was key. The figure below shows the key components of the ASP.NET Core request processing pipeline and how this separation is achieved.

image Every ASP.NET Core application runs within an in-process HTTP Server implementation. This HTTP Server receives the raw HTTP request and converts it to an internal representation by creating a HttpContext object. This object is then used by the web application for further processing.Kestrel is a cross platform web server built on libuv , asynchronous request processing library. This is the default HTTP Server implementation for all ASP.NET Core applications.

Kestrel is a very basic HTTP server and does not have advanced features like

  • Windows Authentication
  • Port sharing
  • Http Access Logs
  • Process Activation
  • Response Caching etc.

This is why its recommended to use the ASP.NET Core Web Server with a reverse proxy. A reverse proxy is a web server exposed directly to the Internet and responsible for forwarding the requests to the appropriate web servers serving the requests. A web server like IIS , Nginx or Apache can be easily configured as a reverse proxy working in conjunction with the ASP.NET Core Web Server.

This model of having a separate reverse proxy and a web server might sound bit cumbersome. But this helps in making the web application framework independent of the operating system and web servers like IIS, Nginx or Apache. This results in a clean separation of concerns with a lightweight HTTP server handling requests / generating responses while the reverse proxy doing rest of the heavy lifting like security related hardening , application start-up etc.

An ASP.NET Core web application cannot be directly hosted in IIS / Nginx / Apache without a server like Kestrel or any custom ASP.NET Core Http Server implementation. This is because ASP.NET Core is designed to run independent of this servers, ASP.NET Core is not meant to adapt to these servers but these servers needs to be configured to act as a reverse proxy and forward request to the ASP.NET Core Web Server.

IIS works as a reverse proxy , forwarding requests to ASP.NET Core using the ASP.NET Core Module ( ANCM). This is a native IIS module which hooks in the request pipeline ,activates the ASP.NET Core process and forwards the request to the ASP.NET Core Web Server. The IIS worker process ( w3wp.exe) and ASP.NET Core runs as two separate processes , ANCM is responsible for restarting in case the ASP.NET Core application crashes.

There is another option for ASP.NET Core Web Server, HTTP.sys.This is Windows only HTTP Server implementation based on HTTP.sys kernel mode driver. However it has some advanced built in features compared to Kestrel like support for Windows Authentication , Port sharing , response caching etc.HTTP.sys kernel driver is a very advanced technology and IIS itself runs on top of it. So this HTTP Server is protected against security attacks etc. and is suitable for running without a reverse proxy for internet facing applications. For intranet applications also this can be good choice given its support for Windows Authentication.

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

Tuples in C#7

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

What is a tuple ? -  A tuple is an ordered group of elements.

Tuple has been there as a data type in most of the functional programming languages like Lisp , Haskell since their inception.

For example in Haskell , tuple provides a mechanism to store multiple values together. One key difference with a List is, tuple allows to store multiple values of different data type.

image

In C#4.0, Generic Tuple class(es) was introduced, the primary intent was to make it interoperable with languages like Python / F#. This also provided an easy way to return multiple values from a method without defining a separate class or structure.

image

The tuple values could be accessed using the Item property of the tuple class as shown below:

image

We will tweak the above code as follows:

image

We will not be able to modify the element values as these Item properties are read-only making the tuples immutable.

image

There are about 8 overloads of Tuple.Create method and 8 Tuple classes allowing us to tuples up to 8 elements.

So far so good , but if I compare the C# snippet with it is Haskell counterpart it looks cumbersome. It looks kludgy , as if some feature has been artificially dumped into the language.

This is further improved in C#7 with elegant syntactic sugar coat and the System.ValueTuple structure doing the work in background.

This feature is now built into the framework (4.7) and if you are using 4.6.2 or earlier,  the package reference to System.ValueTuple needs to be added.

image 

Like me , if you are using Visual Studio Code you just need to run the command “dotnet add package "System.ValueTuple" from the Terminal, followed by a “dotnet restore”.

image

We can now refactor our earlier code using much simpler and more elegant syntax as shown below:

image

The tuple values could be accessed similarly using the Item property as shown below:

image

We can further improve this by leveraging the new feature of providing tuple element names.

image

These element names are used while accessing the values, making the code more readable.

image

Unlike Tuple classes , the ValueTuple structure is mutable and it allows us to modify the values.

image

The decompiled ( by dotPeek) shows how ValueTuple structure is doing it’s job. The code below looks quite similar to what we did earlier with Tuple class. The named tuple elements are implemented using the attribute System.Runtime.CompilerServices.TupleElementNames. TupleElementNames stores the element names as a string array.

image

image

C# 6.0 – nameof Operator

Posted: January 1, 2016 in .NET, C#
Tags: ,

In this post, we will discuss about the C# 6.0 nameof operator.

In the code snippet below we are trying to the details i.e Class & method names whenever a method is invoked. In real life applications we do similar kind of logging using any logging library.

image

The issue here is we have used string literals to refer to the class and method names. As the number of methods and corresponding log entries increases it becomes difficult to track these and also typos etc. may creep in creating more clutter.

In C# 6.0 the nameof operator gives us a provision to get the names of classes, methods,properties, variables etc. in the form of unqualified strings. The changed version of the code using nameof operator is shown below:

image

This gives as better manageability as the tools and IDE can have better track of these names now. Suppose I am renaming the class in that case Visual Studio track this down very easily as shown in the figure below

image

As obvious this is nothing but a very handy syntactic sugar coat. If we take a look into the IL code, we can easily see nothing heavy duty is going on inside. The compiler is simply replacing the nameof calls by the unqualified string literal name of the class and the method.

 

image

Yesterday we were having a discussion about how we can extend Backbone.js so that we can have a separate controller with action methods the way we have in ASP.NET MVC rather putting the callbacks to be executed based on route matching in the Backbone.Router.One point which I mentioned casually is , “Javascript” does not sophisticated reflection like C# so that we can build a Router/Action Selector/Action Invoker/Controller sort of a pipeline.Later I thought that was very casual statement and not a very correct one.The kind of language Javascript is we do not need that kind of reflection and Javascript offers various ways to dynamically invoke functions.In this post we will explore different mechanisms of invoking functions in Javascript. We will start with the following simple code.

image

Here the “execute” function calls “func” and the function “func” defined in T is executed. Now let’s try to tweak the function “execute” in such a way so that it will accept a object  and a function name as parameter and execute that function defined in that object.

image

Here we are using the “apply” function of Javascript which is available for any function object. The definition of apply is as shown below:

apply([thisObj[,argArray]]) where

  • thisObj is the object that will be used as "this" i.e. object on which the function will be invoked
  • argArray is the argument array used to pass argument values to the function which is invoked

obj[func]” retrieves the function object based on the function name from the hash of “obj” and then “apply” is invoked on that function object.

As a next step let’s modify our function to accept few parameters.

image

The parameters are passed using the array p.

There is another Javascript function “call” which can be invoked on any function object to bind a particular object to it. This is defined as:

call([thisObj[, arg1[, arg2[,  [, argN]]]]]) where

  • thisObj (optional) -   The object to be used as the current object on which the function is invoked
  • arg1, arg2, , argN (optional list) -  A list of arguments to be passed to the method.

The main difference with “apply” is in the way the parameters are handled, instead of a parameter array it accepts individual parameters.This makes it rigid compared to “apply”.

The following code shows the use of call.

image

If you are using Underscore.js this can be achieved more easily with _.bind function.

_.bind(function, object, *arguments) where

  • function  is the function object which needs to be invoked
  • object is the current object on which the function is invoked
  • *arguments are arguments values which the function expects

Our sample code is modified with _.bind

image

The _.bind function internally uses apply as shown below.

image