Happy New Year – 2021

As we already entered the new year 2021, I would like to wish you all a very happy, prosperous, and healthy year. We have faced and seen a lot in 2020 that we never imagined even in our dreams. It has affected every person on this planet in one or other way and has been very depressing. The very human nature is to socialize but this pandemic has attacked this and left us isolated. Thanks to the internet which helped us to get connected but I am sure everyone agrees that it is not a replacement. Whatever the situation is, I am a true believer of the ShivaJi’s (A great Indian Warrior and King) lines “After every dark night there is a morning“.

Experts are also saying that we should be ready for these kinds of pandemics in the future as well. So its the time we start focusing more on health, family, and help to preserve nature.

I wish everyone to stay safe, healthy, focus more on the environment, spend time with family, and help others.

Thanks,

Brij

Do you use Template Literals in JavaScript?

String manipulations and formatting is one of the tedious tasks in many programming languages and it is true in JavaScript as well. If you have to write string with some special character like new line, colon etc, code becomes ugly. Let’s see a quick example

Here we can see that to write a text in two lines, we have to write a newline character (\n) at the right place, we cannot simply write it in two lines as it appears in output so actually you cannot visualize the output until you run it. Or you have other options to break it into multiple strings and use + operator as above which may look little similar but doesn’t look clean at all.

As mentioned earlier that there are times when we have to put special characters in the string like colon, quote, double quote, backslash etc and it becomes more ugly and confusing. To get it working, we need to add special escape character (\) every time it appears in the text as

var message = 
'Hello \'Brij\'\n, Did you use special chars in your new post \' Truthy and Falsy in JS\'?' 

Or if you want to write some regex which would be full of special characters.

Template Literals

Earlier there were three literals in JavaScript as Object ({}), Boolean (true or false) and string (” or “”) and starting from ES6, we have one more literal called template literal which is denoted by backtick character (“), it is mostly just below the escape character on keyboard.

Let’s see the above example using the template literal.

Here we can see that we have message appearing in IDE and console exactly same and we didn’t have any escape character.

Template literal also allows to have expressions which could be a normal variable or normal mathematical expression as

Here we can see the JavaScript code in the upper part and then output in the lower part. In the code, we used an expression three places: name, date object and normal addition of two numbers. Each expression should start with a dollar sign ($) as in the example. We can call any JavaScript function and can use other normal expressions like ternary operators.

This kind of capability has been added to C# some time back and seeing a similar feature in JavaScript made me very happy and couldn’t stop myself from sharing it with you all. (look at my signature 🙂 )

Cheers

Wish you all a very Happy New Year- 2020

As we entered the new year 2020, we left the 10s behind, I would like to you wish you all a very happy, prosperous and healthy year. New Year always brings new hopes, bigger dreams with a lot of opportunities. May you rediscover new strengths, garner faith in you, to face the challenges and reach new heights in your career.

I tried something in 2019  and would like to share with you all.

I always wanted to be looked fit and lean but in the last 8-10 years, I was gaining slowly and continuously. Although from time to time I tried to lose weight, tried running in the morning for a few weeks, GM diet, etc it was just like a pause mostly. Last year I made a promise to myself that I will lose at least 25 lbs and made it my first focus. And with proper planning, monitoring my daily intake and regular gym, I was able to reduce around 28lbs in three months which was like a dream come true. So nothing is impossible, everything needs proper focus and rigorous effort. I hope it will motivate you.

Also, I would like to thank to all of my elders, friends, blog readers, audiences for their generous support and candid feedback throughout the year. I hope it will be continued this year as well.

Again, Happy New Year 2020 and have fun.

Cheers
Brij

Truthy and Falsy in JavaScript

Many times, we observe in JavaScript that some values when used in a boolean context, behave as true or false, this is not common in other languages. For many experienced developers, even they get used to it but it is a mystery while for new developers it is confusing.

These are not the boolean values but these are known as Truthy and Falsy values. Any value which behaves as a true value in a boolean context (like conditions, loops), called Truthy and the values that behave as false, are called Falsy values. Internally, JavaScript converts a value to true or false when used in the boolean context and this is called Type Coercion.

This also means that a single value can be used in conditions.

Falsy

As mentioned before, every value in JavaScript returns true and false when it is used in a Boolean context and the values that return false are called Falsy values. There are 7 falsy values in total in JavaScript.

  1. false (the boolean false value)
  2. 0 (number 0 including all decimal or zeroish number such as 0.0, 0.00, 0x0)
  3. 0n (represents bigint)
  4. ” “,’ ‘ (empty strings)
  5. null
  6. undefined
  7. NaN

To test, I wrote a generic function which writes Falsy or Truthy on console  with some examples as

function TruthyOrFalsy(val)
{
  return val ? console.log("Truthy") : console.log("Falsy");
}

// All the below call logs 'Falsy'
TruthyOrFalsy('')
TruthyOrFalsy("")
TruthyOrFalsy(0)
TruthyOrFalsy(null)
TruthyOrFalsy(undefined)
TruthyOrFalsy(NaN)

Now let’s discuss Truthy values.

Truthy

In simple words, any value which is not falsy is truthy. These values return true if used in a boolean context. Some important truthy values are

  1. “0” or ‘0’ (Any non-empty string is a truthy value including just spaces)
  2. ‘false’ (A string with value false)
  3. [] (An empty array)
  4. {} (An empty object
  5. -1 (A negative number)
  6. function() {} (An empty function)
  7. Infinity (infinity value)

Now let’s see some examples

// All the below call logs 'Truthy'
TruthyOrFalsy(' ')
TruthyOrFalsy(" ")
TruthyOrFalsy(" Some text")
TruthyOrFalsy("0")
TruthyOrFalsy(108)
TruthyOrFalsy(-108)
TruthyOrFalsy(Infinity)
TruthyOrFalsy([])
TruthyOrFalsy([0])
TruthyOrFalsy({})

In normal programming, this truthy and falsy behavior can be helpful in writing concise and readable code. The typeof operator with some of these values can be interesting so let’s see

// All the below call logs 'Truthy'
TruthyOrFalsy(typeof(undefined))
TruthyOrFalsy(typeof(null))
TruthyOrFalsy(typeof(NaN))
All the above are truthy value even the values used in typeof operators are falsy. For first, it even returns undefined but it is ‘undefined’ (string undefined) similar for next two examples. Second one returns ‘object’ and third one returns ‘number’.
These truthy values behave differently sometimes when used in comparison. Let’s see few

 

// Any falsy value wrapped under type becomes Truthy
TruthyOrFalsy(new Number(0))
TruthyOrFalsy(new Boolean(false))

// But comparing these truthy logs falsy
TruthyOrFalsy(new Number(0) == new Boolean(false))

Few other objects like [], [0], [[]] etc are although truthy values but returns false when compared with eatch other or even itself like [] == [].

Conclusion

Javascript is an interesting and powerful language and has some unique characteristics. In this post, we covered the truthy and falsy behavior of it. First we discussed all the Falsy values with examples and covered Truthy values later. As mentioned every value which is not Falsy is Truthy but it can be confusing sometimes and we discuss it with some with examples including typeof operator. Finally, we saw a behavior where even a few values are Truthy but returns true when used with ==.

Hope it helps.

Cheers
Brij

Equality Operators in JavaScript: == vs ===

For C# developers, Javascript has always surprised by its weird behavior. In this post, we are going to talk about one of the very common topics, equality check. In C#, we all have used == or != to check the equality and most of us using/used it in JavaScript in the same way. But in JS, it doesn’t behave as per the expectations each time. Because while doing the comparison, if the type of the values are different, then it internally converts it to the same type first, like if we do 0 == “0”, it will return true although number zero and string zero are not equal.  We have another option for equality check as ===. Let’s see the difference at a high level

But before moving further, lets first see the primitive types in JavaScript. It is seven in total.

  1. undefined ( A variable which is declared but no value got assigned to it)
  2. null ( This type just has one value null)
  3. Boolean (true/false as expected)
  4. Number (All the numbers like integers, floats, double, decimal. It also includes Infinity and NaN )
  5. BigInt (New type – use for storing number greater than 2**53 -1 (2 to power 53 – 1)
  6. String (text)
  7. Symbol (A unique and immutable value. Added in ECMA 2015)

Everything else is of object type. Now let’s come to topic and start with loose equality

== (Loose Equality):

As from the picture, == doesn’t care about the type and just checks the value. When we compare the values of different types like a string with a number or number with a boolean etc, it first makes it to the same type by converting the one type to another and then does the comparison. It is also called Type Coercion.  So the return values are based on the content of a variable. Let’s see some examples

console.log("2" == 2) // true
console.log ("2.04" == 2.04) // true
console.log(true == 1) //true
console.log("0" == false) //true
Here we can see in the first example, first value is string and another one is number (There is no type as int in JavsScript as mentioned earlier). Before comparing the value is also converted internally first and the comparison is done which returns true. Same can be seen in the second and third example. In the third example, true value is considered 1 in JavaScript so it returns true as well. In the last example as well, 0 is considered as false (even here is of type string) so both are false which returns true.
Similarly, we can use it’s opposite !=
console.log(2 != "3") // true
console.log(true != 1) // false

=== (Strict Equality):

As type-safety is one of the key features that we want from a programming language, we can use === for comparison in JavaScript. This checks type and value of both variables and accordingly produces the result. Lets see few examples

console.log(2 === 2) // true
console.log("Hello" === "Hello") // true
console.log ("2.04" === 2.04) // false
console.log(true === 1) //false
Here we can see that in the first two examples, the type (number for first and string for the second) and values both are the same so it returns true. In the last two examples, even the values are the same but the type (string and number, boolean and number) are different so it returns false.
This is an expected behavior that we normally want from a program so it is advisable to use === in the day to day coding although this looks little unusual and for a programmer who didn’t see it in past, (s)he may find this as mistake/typo so we may write comment on top of it unless we have included it in the coding guidelines.
It’s opposite the non-equality operator (!==) works as a non-strict equality operator as expected.

Conclusion:

As discussed, we can see that although lots of places == is used for equality check and it works many times as expected, it is advisable to use === for equality checks. Although this can be achieved with == using and additional check of type of both values it doesn’t make any sense. Better to have coding guidelines to use strict equality operator.

Cheers
Brij

Conditional Ref, Ref ReadOnly, Ref Reassignment in C# 7.X

C# has gone through the major changes starting from 6.0 specifically from 7.0. I wrote a list of posts on C# new features which covers key topics that can be used in our day to day programming. You can find the previous posts list below

C# 7.X posts

Today we are going to discuss few uses of ref which provided altogether different meaning to it.

Conditional Ref: This feature was introduced in C# 7.2. Before going to this specific topic, we know that ref keyword has been in C# prior to 7.X and we used this keyword to pass the values by reference as

        static void Main(string[] args)
        {
            TestRef testRef = new TestRef() { Description = "First Object" };
            double price = 20;

            DoSomething(ref price, ref testRef);
            Console.WriteLine(price);
            Console.Write(testRef.Description);

            Console.ReadKey();
        }

        public static void DoSomething(ref double finalPrice, ref TestRef test )
        {
            finalPrice = finalPrice * 1.2;
            test = new TestRef() { Description = "Second Object" };
        }

   public class TestRef
    {
        public string Description { get; set; }
    }

Here I am passing a value type variable price and an object of a class type TestRef (we know classes are reference type). So let’s see the result before discussing it

Here we can see that  finalPrice is passed as ref parameter and when we are updating the value in the method, the updated value is available in caller function as it was passed using ref. Similarly in case of TestRef’s instance as ref parameter, a new instance is assigned to the variable then the variable in caller method also got updated with the new instance. It is because the instance testRef was pass passed using ref.

We have discussed few other usages of ref keyword which got introduced in 7.X, conditional ref are one of the interesting ones. We used ternary operator in past as

    var smallArray = new int[] { 1, 2, 3, 4, 5 };
    var largeArray = new int[] { 10, 20, 30, 40, 50 };

    int index = 7;
    int val = ((index < 5) ? smallArray[index] : largeArray[index - 5]);
    val = 0;

Here val gets assigned with value 0. If we change this value, no update takes place in the original array. Now let’s see the power of ref keyword here. We can see that based on condition first or second value is returned but now we can use ref keyword as

    ref int val = ref ((index < 5) ? ref smallArray[index] : ref largeArray[index - 5]);
    val = 0;

Here I am using the same array but here we are using the ref keyword in Consequent (smallArray), Alternative (largeArray) and put the ref at the whole ternary expression. Also, at left side added ref as ref int val. Removing any ref keyword will produce an error. If we want to store it as normal value then we may remove ref from left and outer ref from right.

Now val is pointing to the largeArray[2] and as we assigned it to 0, array also got updated.

Also as these ternary operator refers to a memory location so we may use it as LValue as

    ref ((index < 5) ? ref smallArray[index] : ref largeArray[index - 5]) = 0;

ref readonly: I discussed about ref keyword in one of my previous posts (refer here). It allows us to pass the values by reference, return the value by reference. But what about if we want to return a value which we dont want to get modified by the caller. Either we pass it by value (which creates a copy ) or we can use ref readonly. It will make sure the reference is returned (not the copy) but caller cannot modify the returned value. Let’s see an example


static void Main(string[] args)
{
    var points = new Point[] { new Point(1,2), new Point(1, 2), new Point(1, 2) };

    var point = new Point();
    point.SetPoints(points);

    ref readonly var myPoint = ref point.GetPoint(2);

    // It is a compile time error
    myPoint.Y = 10;

    Console.ReadKey();
}
	
struct Point
    {
        public int X;
        public int Y;

        public Point(int x, int y)
        {
            X = x;
            Y = y;
            points = null;
        }

        private Point[] points;

        public void SetPoints(Point[] arrPoint)
        {
            points = arrPoint;
        }

        public ref readonly Point GetPoint(int index)
        {
            if (points.Length &amp;gt; index)
                return ref points[index];
            else
                throw new KeyNotFoundException();
        }
    }

Here you can see GetPoint method in struct which returns one of the points from the array using ref keyword. Now if we want that the caller should not be able to modify it, then we need to put ref readonly in return type (not while returning). Now if you see while calling, we have to use ref on the right side and ref readonly on the left side and changing that variable would be a compile time error. As the method return ref readonly we cannot remove readonly from left side, however we can completely remove ref from both side including readonly then it will create a copy of the point.

If you remember In (about In)operator which allows the variable pass by reference but called method can’t modify that, it is opposite as Caller cannot modify the returned variable however the keywords are bit different.

As I used struct for the example which is value type and using operators like ref, In etc makes sure that we dont create a copy of that. However we know value type are easy to initialize and destroy in memory but Microsoft recommends that if the size of the struct is more than System.IntPtr.Size then we should avoid creating the copy of the struct.

Tip: Use the ref readonly for large structures and top preserve the immutability of the data structure.

Ref ReAssignment – This feature was added in C# 7.3 which allows us reassign a ref local variable to different location and obviously that should be of same type. Lets see an example

In this example I am going to use earlier Point class and just removed readonly from GetPoint method.

Here we can see a C# 7.2 feature where we get the reference of an array via ref and if we update the ref variable via another ref instance, it updates the original array as we can see in the tool tip.

Ref reassignment allows us to update ref local variables to different location which was not possible prior to C# 7.3 as

Here we can see refPoint was referencing to the last element of the array and once we assign to the first element, it started referring to the first object. This code will work only C# version is selected as 7.3.

As mentioned earlier, C# 7.X and 8.0 has lots of new features and few important ones we discussed earlier. In this post, we discussed three important features related to ref- Conditional ref, ref readonly, ref reassignment. Hope you have enjoyed the post.

Thanks
Brij

 

Hosting ASP.NET Core Applications on IIS : In-process hosting

In my previous blog post, I discussed a brief history about ASP.NET Webforms/MVC applications and its deployment to IIS. Then we took a look in the new framework ASP.NET Core which was introduced keeping in mind the performance and cross platform readiness. As performance was one of the key drivers, they introduced entity framework core and all thenew web server named Kestrel. You can read the blog post here.

Hosting ASP.NET Core Applications on IIS – A Detailed Look

We discussed about ASP.NET MVC Core 2.1 and discussed some internal details about its deployment on IIS as a reverse proxy (which is recommended), and also took a look on using Kestrel as an Edge Server. Although Kestrel is matured enough to be used as an Edge Server but still IIS is considered better option. We also saw, how ASP.NET Core requests are handled by IIS. We need to install the .NET Core Hosting bundle (download here) which adds a module named ASP.NET Core Module  (ANCM). ANCM is responsible to route the asp.net core request to Kestrel.

With ASP.NET Core 2.2, Microsoft introduced In-process hosting. This model allows us to host the asp.net core 2.2 directly inside the worker process (w3wp.exe) which is similar to earlier ASP.NET version. Let’s take a pictorial view

We can see that there is no dotnet.exe is involved here in the second part. All the components ANCM, CoreCLR and application code are loaded in same worker process.

To use the latest feature, we need to install the latest 2.2 bundle (download here) which installs the upgraded version of ANCM also referred as ANCMv2. After installation, both the modules can be seen in IIS modules section as

Why new version of ASP.NET Core Module (ANCMv2)?

Earlier the idea with ANCM to use IIS as a reverse proxy and leverage Kestrel as a backend web server (as it was not hardened enough as an edge server) but as Kestrel got all the required enhancements, MS reworked on ANCM so that IIS can be used another platform to host asp.net core applications without the need of Kestrel. ANCM got redesigned and divided in two components, a shim and a request handler.

     Shim – As the name suggests, it is a very light weight component which is continue to be installed as a global module via bundle which just work as an interface between IIS and request handler.

   Request Handler – Request Handler is now an independent component which does all the work and can be updated via nuget. We can have multiple versions of request handler side by side. It means we can have multiple application using its own request handler.

With earlier ANCM, it was available as global singleton module which is shared by all the application which is a major bottleneck in releasing newer versions as it has to support every application. With the new architecture, we also get better process management, performance enhancements and easy updates via nuget.

We have so many benefits with the new model however we have one limitation – one application pool can only host only one application (In ASP.NET Web Form/MVC we could share app pools with multiple applications) as we don’t have the concept of Application domains in CoreCLR and this feature supports to CoreCLR only.

Let’s see an example

Now I have created another sample web application application using ASP.NET Core 2.2 (used VS 2017 v15.9.4) and deployed to IIS after publishing that.

There is no brainer here, let’s see the processes

Just to compare with earlier version I am adding both here.

So we can see the difference, in first scenario (<ASP.NET Core 2.2) the application is running under dotnet.exe while in second scenario, it is running under the worker process (w3wp.exe) itself which boosts the performance significantly as we don’t have to manage the dotnet process (earlier approach could have reliability issues as well) and request doesn’t have to travel outside of the process.

ASP.NET Core 2.2 allows out of process deployment as well. When we publish our application, it generates a web.config which has following xml node

<aspNetCore processPath=”dotnet” arguments=”.\InProcApp.dll” stdoutLogEnabled=”false” stdoutLogFile=”.\logs\stdout” hostingModel=”InProcess” />

Here hosting model at the end defined as InProcess. We can change it to OutOfProcess which would be similar as earlier one and application would be running using dotnet.exe. These configuration can also be set via Visual Studio while debugging as

Go to Solution Explorer -> Right Click on project-> Debug (tab)-> Web Server settings section

Performance comparison

As mentioned above, with ASP.NET Core 2.2 allows us to host both the In-process and Out-of-process model (It is similar to earlier version). I have done sample load test using the Netling (know more about this tool here) and for out-of-process result is here

We can see that 2576 request got served per second. I changed the hosting as In-process and ran the same test again and the results are

Here we can see that request per second got increased significantly to 3742 which is approximate ~50% increase. Other data points like median, stddev also got reduced significantly. Itmay vary based on the scenario as I ran it on a developer VM and the application used was a default sample application using asp.net core 2.2 (not an empty application). However, Microsoft ran the test in performance labs where they got 4x throughput with In-process hosting.

Conclusion

Even kestrel was introduced with ASP.NET Core as a highly performant web server or as an alternate to IIS, it was always suggested to use IIS as frontend server in windows environment. Initially, many important features were missing in Kestrel which got added with the release of asp.net core 2.0 and 2.1, still IIS is advised to use for enterprise environment and internet facing application mainly due to security and stability reasons. There were several bottlenecks with having two different processes (w3wp.exe and dotnet.exe) and the way like port conflicts/not available, process management etc. All these can be avoided using In-process hosting model.

Cheers
Brij

Hosting ASP.NET Core Applications on IIS – A Detailed Look

In last few years, I spent a significant amount of time researching, writing, speaking on ASP.NET application’s performance. Performance of a web app is not just its code but it depends a lot on the hosting platform, configurations and the usage of available resources etc. If you are hosting ASP.NET Webforms/MVC application on IIS, then you can follow below tips and get benefitted quickly.

12 tips to increase the performance of your ASP.NET application drastically – Part 1
12 tips to increase the performance of your ASP.NET application drastically – Part 2

Whenever I think about the performance of any web application, there are three major areas comes into my mind (I am not considering the external factors)

  1. Hosting Server
  2. Application itself
  3. Database/Third Party APIs etc

Any application can’t be highly performant until all three are properly optimized. It can perform better if all were taken in consideration in early stages development lifecycle.

ASP.NET Web Forms is/was very popular web framework but it has many known performance issues. To overcome many and to use latest standards and best practices, Microsoft introduced ASP.NET MVC framework. Over time, Microsoft sensed the need of new highly performant cross platform web framework to compete in market and introduced the all new ASP.NET Core framework (Initial Name: ASP.NET 5) which is written from scratch. Although at a high level, most of the constructs are similar with ASP.NET MVC but the underlying engine got completely rewritten.

While working on ASP.NET Core, MS worked on the complete stack, like for backend – they introduced Entity Framework core and for hosting the application, a new highly optimized web server, known as Kestrel. But as we know IIS provides an array of features, configuration and battle tested for all kind of scenarios, Kestrel was not ready as an edge server.

Although the new server was introduced with ASP.NET Core but it appears that initially, the main focus was on ASP.NET core and other backend frameworks. During ASP.NET 1.X, it was advised to used IIS as frontend server which in turn forwards the requests to Kestrel. A reverse proxy was suggested due to security and reliability reasons. It didn’t have defense against attacks and other configurations like various timeouts, size limits, concurrent connection limits etc. So, we only had the option to deploy the application using IIS (Nginx, Apache for other platforms) as reverse proxy. In the newer versions (ASP.NET Core 2.X), lot of enhancements has been made in Kestrel and with ASP.NET Core 2.1 and later, Kestrel started supporting https (which is nowadays basic requirement for hosting any web application on internet). Now it can be used as internet facing server . In this post and coming post, we will discuss the available deployment options with IIS and explore that what is happening behind the scene.

Using IIS as a Reverse Proxy:

In this scenario, ASP.NET Core application is hosted on kestrel which sits behind IIS. At a high level, it looks like

 

 

 

I created an asp.net core sample application which I deployed on IIS. Let’s take a quick look into the steps for deployment.

  1. First, we need to configure IIS on Windows (if it’s not there).
  2. Install the .NET Core Hosting Module (Can be downloaded from here based on the versions).  After installation, you can go to the IIS modules section and ANCM will appear as
  3. Create the website at IIS
    1. Create a folder which will contain app’s published folders, files and binaries
    2. Create a new logs folder inside the earlier created which will contain the logs created by ASP.NET Core module when stdout is enabled.
    3. In IIS, Add a new Website by right clicking on Sites folder under Connections -> ServerName as NetCoreProxy (say).
    4. It by default creates a new application pool named as preferably -. Go to application pools under Connections-> Server Name and Click on NetCoreProxy. Select “No Managed Code” under .NET CLR version 
      “No Managed Code” why? We will discuss it later.
    5. Check the identity which is by default as “AppPoolIdentity” and change it if needed.
  4. Last step, publish the website by Right Clicking on the project in Visual Studio in the newly created folder at 3 a.

Publishing the ASP.NET Core App

While publishing an ASP.NET Core app, we need to select the deployment mode option which has two options: Framework dependent and Self-Contained. Publishing with second option produces a significantly larger binaries because it contains the coreclr and other required system libraries. This should not be a preferred option until necessary because of the huge size and performance implications as it loads all the resources and JIT them on the fly.

Now we should be able to browse our ASP.NET core web site.

Let’s take a look in details

The first question that arises is why do we need to install something on IIS? One of the problems with earlier versions of ASP.NET, that ASP.NET and IIS both has its own pipeline which contains multiple modules (IIS pipeline contains native and managed modules) and each request has to go through both the pipelines invoking each module (However this problem was resolve till certain extent using Integrated Pipeline setting at IIS). Most of the times, many of them are not used by the appliccation. Using ASP.NET Core, we got a new pipeline which has list of middleware that are added at application startup based on the need. To avoid all the IIS overheads, when we install the bundle on IIS, it adds a native module AspNetCoreModule (ANCM) which is invoked at very early stage and forwards the requests to Kestrel as soon as it reaches to IIS. Earlier it was done by an existing module called HTTP Platform Handler which used to forward the request but MS decided to create a new native module ANCM which was fork of HTTP Platform Handler to have better control and able to provide tailored features.

Also, we have seen in deployment steps that we selected “No Managed Code” while configuring the application pool, it means we don’t want to run any managed modules for the requests of this application. As mentioned earlier, IIS pipeline contains the native and managed modules both, ASP.NET core requests do go through some of the native modules like authentication modules (Anonymous, basic, Windows etc), dynamic compression etc. Few native modules are not part of the process and as many of them has a corresponding asp.net core middleware (for details, look here). Let’s take a look that how does it work

We can see here that ASP.NET core app runs into a different process dotnet.exe, not in the worker process which was the case with earlier versions of ASP.NET. I also used the process explorer to see it

Here we can see that dotnet.exe is a different process which runs the application. What is this Console Host process? If we take a look in ASP.NET core’s startup class, we will see a main method, similar to console application which is the first method which gets called when the application starts.

Let’s go through step by step process, how a request is served in this scenario

  1. The request is received by the HTTP.sys from the network.
  2. If response is cached at HTTP.sys then it is sent back from there else gets a place the corresponding Application Pool’s queue.
  3. When a thread is available in the thread pool, it picks up the request and start processing it.
  4. The request goes through IIS processing pipeline. As mentioned earlier the request goes through few native IIS modules and once it reaches to ANCM, it forwards the request to Kestrel (under dotnet.exe).
  5. ANCM has a responsibility to manage the process as well. If (re)starts the process (if not running or crashed) and IIS integration middleware configure the server to listen the request on port defined in environment variable. It only accepts the requests which originates from ANCM.
    Note -Please do note that in ASP.NET Webforms/MVC the application is hosted under the worker process w3wp.exe which is managed by Windows Activation Service (WAS) which was part of IIS.
  6. Once the request is received by Kestrel, it creates the HTTPContext object and request is handed over to ASP.NET Core middleware pipeline.
  7. The request is passed to routing middleware which invokes the right controller and action method (model binding, various filters almost similar way as earlier versions).
  8. Finally, the response is returned from the action and passed to kestrel via Middlewares and later sent back to client via IIS.

So we can see the request processing is quite different than earlier versions ASP.NET apps hosted on IIS.

Using Kestrel as an Edge Server

With ASP.NET Core 2.1, Kestrel got lots of new capability which makes it capable of using it an edge server, however for the enterprise level application, it is still recommended to use it behind a proxy. Obviously, one of the first choices is using IIS in windows environment. With ASP.NET Core 2.2, It got some more refinement which makes IIS a better option. We will discuss that in next blog post. Kestrel as an edge server looks like

As this post is specific to IIS hosting, I will not go into the detail but earlier lots of important web server features like Keep alive timeouts, connection timeout, body reading timeouts, request timeouts, size limits, concurrent connection limits, memory limits etc were not available but now most of the configuration can be done and it supports https as well. Even with that Microsoft suggests using IIS as a reverse proxy due to additional feature, security, configurations and many more.

Hope you have enjoyed the post. Do share the feedback. In next post, We will discuss the In-process enhancement  in ASP.NET Core 2.2 in detail.

Cheers
Brij

Wish you all a very Happy New Year – 2019

As 2018 comes to an end and we have just entered to 2019, I would like to wish you and your families a very Happy New Year. New year brings new ideas, new challenges and lot more opportunities. May you rediscover new strengths, garner faith in you, to face the challenges and reach to new heights in your career.

Heartiest thanks to all my elders, readers, subscribers and followers for the kind support and continuous feedback. I will strive to spend more time and add value to community.

Wish you all again a very Happy New Year!

Cheers,
Brij

Received Microsoft Most Valuable Professional award 8th time in a Row

Hello friends,

I am very happy to share with you all that I have been awarded as Microsoft Most Valuable Professional for 2018-2019 in Visual Studio and Devlopment Technologies category. This has been 8th award in a row and this wonderfull journey started on 1st July 2011.  Since then 1st July have been a very special day for me as this is the announcement date and day for refreshing the inbox n number of times. I sincerely thank Microsoft for the award and Continuous recognition.

Also, I want to take this opportunity to thank all my readers, followers, seniors and friends throughout these years. It has never been possible without your candid feedback throughout these years.

Initially, I got this award way back in July 2011 in ASP.NET/IIS category which got changed to Visual Studio Development Technologies in 2016. This has been a long and very exciting journey and I have enjoyed each year as part of community and connecting all of you in various ways.

If you also want to know more details about this award you can refer MVP Award Home page and want to get this prestigious award then get the details from here. You can also contact me for any specific details on my email id brij.mishra [at] outlook [dot] com or tweet me at @code_wala and I will be very happy to guide you.

At last, I would say that I’ll devote more time to community with the same intensity and share my knowledge in different ways and learn from all of you. Your feedback is utmost important for me that I’ll seek every time.

Thanks again to all of you for your feedback and support.

Cheers,
Brij