Archive for the ‘.NET’ Category

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.

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.

The code snippet of FindMethod is shown below.

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.

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#?

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.

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.

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

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

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:

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.

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

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.

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.

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.

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

We will tweak the above code as follows:

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

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.

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”.

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

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

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

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

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

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.

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.

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:

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

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.

ASP.NET 4.5 has introduced model binding and strongly typed templates for ASP.NET server controls.This simplifies the way a plain .NET object can be bound as a datasource of a server control like a GridView.Let’s get started off with a simple example of how model binding works.

Singleton is the most widely known Design Pattern. Singleton makes sure that one only one instance of a class is created and the same instance is used by other programs and classes.An implementation of a Singleton class is shown below: