Posts Tagged ‘.NET’

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.

This week I came across a problem related to structuring an ASP.NET MVC Web application one development team was facing. What they were trying to do was quite simple: to create a folder structure each having their own subfolders for View/Controller/Scripts/CSS etc. The application resources like JS/CSS etc. were not getting rendered properly. The issue was due to Web.config file lying under the subfolder, which when moved to the Views folder under that subfolder things went fine. The purpose of this post is not to discuss about the details of that problem and it’s solution.But to discuss about how we can easily structure our ASP.NET MVC Web application as per different modules, which is an obvious need for any large application.

ASP.NET MVC follows the paradigm of “Convention Over Configuration” and default folder structure and naming conventions works fine for a smaller application. But for relatively bigger one there is a need to customize.The framework also provides enough provisions for the same.You can have your own controller factory to have custom ways to creating the controller classes and custom view engine for locating the rendering the views. But if the requirement is to structure the application to different subfolders as per modules or subsites  I think the use of “Area” in ASP.NET MVC will be helpful to create a streamlined application.

You can add an Area to a ASP.NET MVC project in VS as shown below.



Here I have added an area named “Sales”. As shown in the figure below a folder named “Areas” is created with a subfolder “Sales”. Under “Sales” we can see the following

  • The standard folder of Models/Views/Controllers
    • A Web.config under the Views folder. This contains the necessary entries for the RazorViewEngine to function properly
  • A class named SalesAreaRegistration.


The code (auto generated) for the SalesAreaRegistration class is shown below:

public class SalesAreaRegistration : AreaRegistration 
    public override string AreaName 
            return "Sales"; 

    public override void RegisterArea(AreaRegistrationContext context) 
            new { action = "Index", id = UrlParameter.Optional } 

System.Web.Mvc.AreaRegistration is the abstract base class use registering the areas into the ASP.NET MVC Web Application. The method void RegisterArea(AreaRegistrationContext context) needs to be overriden to register the area by providing the route mappings. The class System.Web.Mvc.AreaRegistrationContext encapsulates the necessary information (like Routes) required to register the area.

In Global.asax.cs Application_Start event we need to RegisterAllAreas() method as shown below:


The RegisterAllAreas method looks for all types deriving from AreaRegistration and invokes their RegisterArea method to register the Areas.

Now with the necessary infrastructure code in place I have added a HomeController and Index page for the “Sales” area as shown below.



Now I am trying to run the application and got the following error: [NOTE: This has nothing to do with areas but because I have two controllers with same type name i.e. HomeController]

Multiple types were found that match the controller named ‘Home’. This can happen if the route that services this request (‘{controller}/{action}/{id}’) does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the ‘MapRoute’ method that takes a ‘namespaces’ parameter.

The request for ‘Home’ has found the following matching controllers:



I have to change the Route Registration for the HomeController to avoid conflicts and provide the namespace information as shown below:

public static void RegisterRoutes(RouteCollection routes) 

                "Default", // Route name 
                "{controller}/{action}/{id}", // URL with parameters 
                new { controller = "Home", action = "Index", id = UrlParameter.Optional },// Parameter defaults 
                new String[] { "AreasDemo.Controllers" } 

Now I will add a link to the Sales area by modifying the _Layout.cshtml as shown below:

<li>@Html.ActionLink("Sales", "Index", "Home", new { area="Sales"},null)</li>

Here I am navigating to the area “Sales” from the main application so I have to provide area information with routeValues. The following overload is being used in the code above:

public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes);

For navigating within the “Sales” area however routeValues will not be required.

Custom Layout in WPF

Posted: March 14, 2010 in .NET, WPF
Tags: ,

The layout system in WPF is responsible for measuring and arranging the user interface elements within the panel and displaying them on screen.This is a two phase process.In the measure phase the panel will measure what is the amount of space required by each of it’s children, in order to find out the total space required.In the next arrange phase it will find out how much space it actually has and accordingly render the elements as per predefined logic.


Covariance & Contravariance – Delegates in C#

Posted: November 30, 2008 in .NET
Tags: ,

In my last post I had discussed about delegates in C# but intentionally skipped the covariance and contravariance with respect to delegates.I would like to discuss the concepts of covariance and contravariance in general first and then correlate the same in context of C# delegates.The concept of covariance and contravariance I found a bit confusing and counterintuitive initially.

Let us consider a type/class P and let P” be a subtype/subclass of T.We will denote this relationship as P”->P for sake of discussion.Based on this inheritance relationship following statements are true:

  1. Domain of P is much broader than P”.
  2. Any context where P is expected we can substitute it by P” [Liskov Substitution Principle]

Similarly we have another pair of classes R and R” where R”->R.

Now we will consider a function f which type P as parameter and returns type R.We will denote this as R f(P).Similarly there is another function f” as R”f”(P”) which accepts P” as parameter and returns type R”.

Can we say that f”->f or we can replace f by f” in any context?

In order to replace f by f”, f” should be able to handle parameter of type P and return value of type R.

Now R” is a subclass of R,so R” is a type of R.Hence we can say f” basically returns a type R.This is covariance by which we can replace a method by another having a more derived return type.

Now let’s see can f” handle a parameter of type P.The answer is NO.The logic built into f” is only for the possible values of P” and P can have more possible values than P” as it is the super class.So f” will malfunction for all those values of P which are outside the range of P”.So f” can replace f only if parameter of f is more derived than that of f”.This is contravariance by which we can replace a method by another having parameter types that are less derived.

If we redefine f as R f(P”) and f” as R” f”(P) then we can say f”->f and can replace f in any context.

Now let us consider an example with some real life examples.

There is a base class called Order and Order can be of two derived types say SalesOrder and PurchaseOrder.Similarly there is a base class called AccountRecord and there are two derived classes say AccountPayable and AccountReceivable.

There are two methods

  1. M1 – AccountRecord GetAccountInfo(Order o)
  2. M2 – AccountPayable GetAccountInfo(PurchaseOrder po)

M2 cannot accept a variable of type O as parameter because if it is an instance of SalesOrder instead of PurchaseOrder this will fail.

But calling code which expects AccountRecord as output can very well handle both AccountPayable and AccountReceivable.

We can relate this to a delegate in the following way:

public delegate object ReadObjectDelegate(FileStream fs)

We can attach the following method to this delegate

public string Read(Stream s)

This is because Stream is less derived than FileStream and string is more derived than object

Delegates in C#

Posted: November 29, 2008 in .NET
Tags: ,

Most of us quite familiar with the delegate keyword in C#.Delegates provides us with a mechanism to encapsulate a method or multiple methods.These are quite like managed version of function pointers in C#.We normally use delegates to define callback methods.

First we need to define a delegate as a type with it’s signature as shown below.Note here the signature includes both parameters as well as return values.

public delegate void DemoDelegate(int i);

To use the delegate we need define a variable to type DemoDelegate ,instantiate the variable by passing a method name of matching signature and then invoke the delegate by passing suitable parameter values as shown in the snippet below:

class DelegateSample
       public void ShowDemo()
          DemoDelegate d = new DemoDelegate(Test); //Create instance
           d(10); //Invoke delegate
       public void Test(int i)
           Console.WriteLine(“Method Test called with parameter ” + i);

Now if we take close look into the syntactic details we see all the operation related to delegate closely resembles that of a reference type.So what’s going on inside.On taking a look into the IL code of the assembly we found a new class is generated as shown below:

.class /*02000003*/ public auto ansi sealed DelegateDemo.DemoDelegate
       extends [mscorlib/*23000001*/]System.MulticastDelegate/*01000002*/

} // end of class DelegateDemo.DemoDelegate

So the C# compiler internally generates a class with the same name as the delegate type and it inherits from a class System.MulticastDelegate.The class System.MulticastDelegate is derived from base class System.Delegate.This method provides two public attributes

  1. Method – Metadata Method which is getting executed as an instance of System.Reflection.MethodInfo
  2. Target – Stores the instance on which delegate method executes.

Before we proceed further let us take a quick look into another feature of delegate chaining.Refer to the sample below and refer to the lines marked in red.

class DelegateSample
      public void ShowDemo()
          DemoDelegate d1 = new DemoDelegate(Test);
          DemoDelegate d2 = new DemoDelegate(Demo);
          Console.WriteLine(“Delegate Added”);
          DemoDelegate d3 = d1 + d2; //Two delegates are combined
          d3(10); //First method  Test and then Demo is invoked
          Console.WriteLine(“Delegate Removed”);
          DemoDelegate d4 = d3 – d1; //One delegate is removed from the combination
          d4(10);  //Only method Demo is invoked as delegate d1 is removed.
      public void Demo(int i)
          Console.WriteLine(“Method Demo called with parameter ” + i);
      public void Test(int i)
          Console.WriteLine(“Method Test called with parameter ” + i);

What happens when I do + and – operation on delegates.Internally the methods System.Delegate.Combine and System.Delegate.Remove is invoked by the runtime.This we can see in the IL code of the show demo method:

.method public hidebysig instance void  ShowDemo() cil managed


  IL_0028:  call       class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate,
                                                                                          class [mscorlib]System.Delegate)

  IL_0049:  call       class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate,
                                                                                         class [mscorlib]System.Delegate)

} // end of method DelegateSample::ShowDemo

WCF Web Model – POX/JSON Support

Posted: October 28, 2008 in .NET, WCF
Tags: , , , ,

For the past few days I was studying the details of the Web Programming Model of WCF.This feature enables WCF services to be called using simple HTTP requests i.e. without the messages wrapped in SOAP format.The messages can be POX(Plain Old XML) or JSON(JavaScript Object Notation).So the client for this kind of services does not need any specific proxy or WSDL.But how client is made aware of the service metadata is still a question to me.However parking that question aside for now let us get into, step by step how this feature is built using the extensibility points provided by WCF infrastructure.

Client Side

Let us first think of what the client is going to send to the service?Just a HTTP request.The method may be GET or POST.Suppose I am trying to access a service operation Add(int i,int j) .The client code in C# will be something like as shown below:

HttpWebRequest  request =  HttpWebRequest.Create(http://localhost:9001/Test/Add/?i=1&j=1) as HttpWebRequest;
request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.None;
request.Method = “GET”;
request.ContentType = “text/xml”;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Before we proceed into the details of the service side let me note the down the questions that initially occurred to my mind.

  1. How the HTTP message will read and parsed in the service side?
  2. How from the URI the name of the method Add will be read and request will be dispatched to the correct operation?
  3. How the parameters will be parsed from the querystring?

In the subsequent sections I will try to answer these questions.

Service Side


In the server side there should be some program listening to a particular socket waiting for bytes to arrive.This is the job of the ChannelListener as I had discussed in one of my earlier posts titled ServiceHost & Channels.This ChannelListener should be able to read raw bytes and create channels to process the HTTP requests.But the channels are created by the specified binding.So we need a binding which can handle HTTP Transport and encode/decode POX and JSON messages.For this we have a binding provided by WCF called WebHttpBinding.This binding is primarily composed of HttpTransportBindingElement and WebMessageEncodingBindingElement.This WebMessageEncodingBindingElement inherits from TextMessageEncodingBindingElement and is a composite encoder which can handle plain text,XML,JSON and raw binary data.

So to make WCF Services available for basic HTTP clients we need to expose an endpoint with WebHttpBinding.


Now we have an service endpoint ,message is processed by channels created by WebHttpBinding and routed to the EndpointDispatcher via the ChannelDispatcher.But who reads the URI of the message and decides which service operation this is intended for?How the parameters values are parsed from the querystring?

The parsing of URI and determination of operation is done by public string SelectOperation( ref Message message ) method of a  WebHttpDispatchOperationSelector class implementing the IDispatchOperationSelector interface.

The querystring parsing and parameter processing is done by a dispatch formatter class implementing the IDispatchFormatter interface with methods:

void DeserializeRequest(Message message, object[] parameters)
Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)

How these two classes gets attached to the DispatchRuntime of the EndpointDispatcher.WCF allows to modify the behaviour of an endpoint using endpoint behaviours.The classes intending to so needs to implement the IEndpointBehavior interface.WCF provides WebHttpBehavior class for modifying the endpoint behavior to suit the needs of POX/JSON messages.This class has three methods to get the operation selector and formatters.

protected virtual WebHttpDispatchOperationSelector GetOperationSelector(ServiceEndpoint endpoint)
protected virtual IDispatchMessageFormatter GetReplyDispatchFormatter(OperationDescription operationDescription,ServiceEndpoint endpoint)
protected virtual IDispatchMessageFormatter GetRequestDispatchFormatter(OperationDescription operationDescription,ServiceEndpoint endpoint)

In the operation ApplyDispatchBehavior these components are added to the DispatchRuntime

public void ApplyDispatchBehavior(ServiceEndpoint serviceEndpoint, EndpointDispatcher endpointDispatcher)

      endpointDispatcher.DispatchRuntime.OperationSelector = …

How the WebHttpBehavior is added to the ServiceEndPoint??


WCF provides a class called WebServiceHost to host services for web based clients send POX/JSON messages.This class inherits from the ServiceHost class.This class makes sure that WebHttpBinding is properly used and attaches the WebHttpBehavior to the ServiceEndPoint.

Now the last things that I need to mention is the two Operation Behavior attributes that need to be applied to the Service operations:WebInvokeAttribute and WebGetAttribute.These two attributes are passive operation behavior and adds some additional metadata to the operation description.This information is used by the WebHttpBehavior for processing.WebGetAttribute allows only HTTP GET requests whereas WebInvokeAttribute has one Method parameter.This parameter is set to POST by default and can accept GET and PUT as well.

The method signature of the Service operation will look something like:

int Add(int x, int y);

We have covered almost the entire flow of POX/JSON messages from client to service.

In the next post I will discuss how to extend this framework and plug in custom functionalities…